Arun
Arun

Reputation: 180

Writing data to csv file in node.js results in weird chinese characters in the resulting csv file

I am trying to write an array of objects into a csv file in node.js. I have the following code:

fs=require('fs');
const  data=[{name:'John'},{name:'Peter' }];
fs.writeFile('test.csv', data, 'utf8', function (err) {if (err)
{console.log('Some error occured - file either not saved or corrupted file saved.');
} else
{console.log('It\'s saved!');
}});

However when i open the saved csv file I have weird chinese characters only in the file. Would anyone have a clue what's going on here?

PS: I am on Windows; node version is 10.15.0

Upvotes: 0

Views: 909

Answers (1)

Ikechukwu Eze
Ikechukwu Eze

Reputation: 3131

The data has to passed as a string - You can use JSON.stringify() to convert JavaScript Object(including Arrays) to a string.

https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

const fs = require('fs');
const  data = [{name:'John'},{name:'Peter' }];
fs.writeFile('test.csv', JSON.stringify(data), 'utf8', function (err) {if (err)
{console.log('Some error occured - file either not saved or corrupted file saved.');
} else
{console.log('It\'s saved!');
}});

Note: From the data you are passing, this wouldn't be a csv file, most likely a JSON file.

Upvotes: 3

Related Questions