使用 Node.js 将对象写入文件 [英] Write objects into file with Node.js

查看:52
本文介绍了使用 Node.js 将对象写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 stackoverflow/google 上到处搜索了这个,但似乎无法弄清楚.

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

我正在抓取给定 URL 页面的社交媒体链接,该函数返回一个包含 URL 列表的对象.

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

当我尝试将此数据写入不同的文件时,它以 [object Object] 而不是预期的形式输出到文件中:[ 'https://twitter.com/#!/101Cookbooks','http://www.facebook.com/101cookbooks']就像我 console.log() 结果一样.

When I try to write this data into a different file, it outputs to the file as [object Object] instead of the expected: [ 'https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks'] as it does when I console.log() the results.

这是我在 Node 中读写文件的可悲尝试,尝试读取每一行(url)并通过函数调用输入request(line, gotHTML):

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('
').forEach(function (line){
    console.log(line); 
    var obj = request(line, gotHTML); 
    console.log(obj); 
    fs.writeFileSync('./data.json', obj , 'utf-8'); 
});   

供参考——gotHTML 函数:

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

    if(err){
        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 ) {
                    social_ids.push(href); 
                }; 
            }; 
        })
    };

    return social_ids;
};

推荐答案

obj 在您的示例中是一个数组.

obj is an array in your example.

fs.writeFileSync(filename, data, [options]) 需要数据参数中的 StringBuffer.查看文档.

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'); 

或者:

// writes ['https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks']
var util = require('util');
fs.writeFileSync('./data.json', util.inspect(obj) , 'utf-8');

edit:您在示例中看到数组的原因是节点对 console.log 的实现不只是调用 toString,它还调用 util.格式 查看console.js源码

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

这篇关于使用 Node.js 将对象写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆