这是我的代码:
var data = require('./campSample.json');
var dataArray = data.resultset.result;
var fs = require('fs');
for(var i = 0; i < dataArray.length; i++){
fs.writeFile("./campList", dataArray[i]["-facilityName"], function (err) {
if(err){
return console.log(err);
}
});
}
我正在尝试让for循环遍历数组中的每个项目,获取facilityName,并将facilityName写入文件。当我运行上面的代码时,它只编写数组中第一项的facilityName。有一个更好的方法吗?我正在使用的campSample.json只是一个样本。我想使用的实际数组中有大约4000个项目。以下是campSample.json的内容:
{
"resultset": {
"-count": "4904",
"-resultType": "campgrounds",
"result": [
{
"-availabilityStatus": "N",
"-contractID": "GA",
"-contractType": "STATE",
"-facilityID": "530145",
"-facilityName": "A. H. STEPHENS STATE HISTORIC PARK",
"-faciltyPhoto": "/webphotos/GA/pid530145/0/80x53.jpg",
"-latitude": "33.5633333",
"-longitude": "-82.8966667",
"-shortName": "C145",
"-sitesWithAmps": "Y",
"-sitesWithPetsAllowed": "Y",
"-sitesWithSewerHookup": "N",
"-sitesWithWaterHookup": "Y",
"-state": "GA"
},
{
"-availabilityStatus": "N",
"-contractID": "OH",
"-contractType": "STATE",
"-facilityID": "960023",
"-facilityName": "A.W. MARION STATE PARK",
"-faciltyPhoto": "/webphotos/OH/pid960023/0/80x53.jpg",
"-latitude": "39.6336111",
"-longitude": "-82.8747222",
"-shortName": "P023",
"-sitesWithAmps": "Y",
"-sitesWithPetsAllowed": "Y",
"-sitesWithSewerHookup": "N",
"-sitesWithWaterHookup": "N",
"-state": "OH"
},
{
"-availabilityStatus": "N",
"-contractID": "NRSO",
"-contractType": "FEDERAL",
"-facilityID": "72346",
"-facilityName": "ACKER ROCK LOOKOUT",
"-faciltyPhoto": "/webphotos/NRSO/pid72346/0/80x53.jpg",
"-latitude": "43.0523056",
"-longitude": "-122.6456111",
"-shortName": "ARCL",
"-sitesWithAmps": "N",
"-sitesWithPetsAllowed": "Y",
"-sitesWithSewerHookup": "N",
"-sitesWithWaterHookup": "N",
"-state": "OR"
}
]
}
}
答案 0 :(得分:2)
您应该事先收集所有名称,然后只用一个IO请求将所有名称写入./campList
。
var names = dataArray.map(function(result) {
return result["-facilityName"];
}).join('\n');
fs.writeFile("./campList", names, function(err) {
if (err) {
return console.log(err);
}
});
答案 1 :(得分:1)
来自writeFile
文档:
请注意,在同一文件上多次使用fs.writeFile而不等待回调是不安全的。对于这种情况,强烈建议使用fs.createWriteStream
此外:
异步将数据写入文件,替换文件(如果已存在)。
答案 2 :(得分:0)
根据您的评论,您需要将内容附加到文件,因此以下代码将起作用
var data = require('./campSample.json');
var dataArray = data.resultset.result;
var fs = require('fs');
for(var i = 0; i < dataArray.length; i++){
fs.appendFile("./campList", dataArray[i]["-facilityName"]+'\r\n', function (err) {
if(err){
return console.log(err);
}
});
}