sar*_*kim 67 javascript file-io node.js
我已经遍布stackoverflow/google搜索了这个,但似乎无法弄明白.
我正在抓取给定URL页面的社交媒体链接,该函数返回一个带有URL列表的对象.
当我尝试把这些数据写入到不同的文件,将其输出到文件[object Object]而不是预期的:" https://twitter.com/#!/101Cookbooks ",' http://www.facebook.com/ 101cookbooks ']就像我console.log()的结果一样.
这是我在Node中读取和写入文件的悲惨尝试,尝试读取每一行(url)并通过函数调用输入request(line, gotHTML):
fs.readFileSync('./urls.txt').toString().split('\n').forEach(function (line){
console.log(line);
var obj = request(line, gotHTML);
console.log(obj);
fs.writeFileSync('./data.json', obj , 'utf-8');
});
Run Code Online (Sandbox Code Playgroud)
供参考 - 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;
};
Run Code Online (Sandbox Code Playgroud)
Guy*_*Guy 77
在deb2fast所说的基础上,我还会将一些额外的参数传递给JSON.stringify()以使其格式相当:
fs.writeFileSync('./data.json', JSON.stringify(obj, null, 2) , 'utf-8');
Run Code Online (Sandbox Code Playgroud)
第二个参数是一个可选的替换函数,在这种情况下你不需要这样的函数null.
第三个参数是用于缩进的空格数.2和4似乎是受欢迎的选择.
Jim*_*ert 62
obj 是您示例中的数组.
fs.writeFileSync(filename,data,[options])需要String或者Buffer在data参数中.看文档.
尝试以字符串格式编写数组:
// writes 'https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks'
fs.writeFileSync('./data.json', obj.join(',') , 'utf-8');
Run Code Online (Sandbox Code Playgroud)
要么:
// writes ['https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks']
var util = require('util');
fs.writeFileSync('./data.json', util.inspect(obj) , 'utf-8');
Run Code Online (Sandbox Code Playgroud)
编辑:您在示例中看到数组的原因是因为节点的实现console.log不仅仅是调用toString,而是调用util.format see console.js source
deb*_*ast 17
如果您正在[object object]使用,那么请使用JSON.stringify
fs.writeFile('./data.json', JSON.stringify(obj) , 'utf-8');
它对我有用.
小智 9
根据我的经验,JSON.stringify比util.inspect稍快.我不得不将DB2查询的结果对象保存为json文件,查询返回了92k行的对象,转换需要很长时间才能完成util.inspect,所以我通过编写相同的1000记录对象进行了以下测试使用这两种方法的文件.
JSON.Stringify
fs.writeFile('./data.json', JSON.stringify(obj, null, 2));
Run Code Online (Sandbox Code Playgroud)时间:3:57(3分57秒)
结果格式:
[
{
"PROB": "00001",
"BO": "AXZ",
"CNTRY": "649"
},
...
]
Run Code Online (Sandbox Code Playgroud)
util.inspect
var util = require('util');
fs.writeFile('./data.json', util.inspect(obj, false, 2, false));
Run Code Online (Sandbox Code Playgroud)时间:4:12(4分12秒)
结果格式:
[ { PROB: '00001',
BO: 'AXZ',
CNTRY: '649' },
...
]
Run Code Online (Sandbox Code Playgroud)