sarahbkim sarahbkim - 2 months ago 4
Javascript Question

Write objects into file with Node.js

I've searched all over stackoverflow / google for this, but can't seem to figure it out.

I'm scraping social media links of a given URL page, and the function returns an object with a list of URLs.

When I try to write this data into a different file, it outputs to the file as

[object Object]
instead of the expected:
[ '!/101Cookbooks',
as it does when I
the results.

This is my sad attempt to read and write a file in Node, trying to read each line(the url) and input through a function call
request(line, gotHTML)

fs.readFileSync('./urls.txt').toString().split('\n').forEach(function (line){
var obj = request(line, gotHTML);
fs.writeFileSync('./data.json', obj , 'utf-8');

for reference -- the

function gotHTML(err, resp, html){
var social_ids = [];

return console.log(err);
} else if (resp.statusCode === 200) {
var parsedHTML = $.load(html);

parsedHTML('a').map(function(i, link){
var href = $(link).attr('href');
for(var i=0; i<socialurls.length; i++){
if(socialurls[i].test(href) && social_ids.indexOf(href) < 0 ) {

return social_ids;



obj is an array in your example.

fs.writeFileSync(filename, data, [options]) requires either String or Buffer in the data parameter. see docs.

Try to write the array in a string format:

// writes '!/101Cookbooks', ''
fs.writeFileSync('./data.json', obj.join(',') , 'utf-8'); 


// writes ['!/101Cookbooks', '']
var util = require('util');
fs.writeFileSync('./data.json', util.inspect(obj) , 'utf-8');

edit: The reason you see the array in your example is because node's implementation of console.log doesn't just call toString, it calls util.format see console.js source