Write objects into file with Node.js

后端 未结 6 1693
滥情空心
滥情空心 2020-12-02 10:53

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 re

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 11:26

    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 'https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks'
    fs.writeFileSync('./data.json', obj.join(',') , 'utf-8'); 
    

    Or:

    // writes ['https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/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

提交回复
热议问题