【发布时间】:2015-10-12 21:07:56
【问题描述】:
我正在尝试在 grunt-search 回调中编写一个新文件。
该过程获取和对象,遍历它以获取一些数据,创建一个新数组,然后将该数组写入 JSON 文件。写作部分不太好……
// onComplete is the callback, job is a returned object.
onComplete: function(job) {
console.log("Creating file \"localize_template\"...");
var fs = require('fs');
var localArray = {};
var foundEntries = job.matches;
var stringCount = 0;
// Drill down to the strings that matched the search.
for (var foundEntry in foundEntries) {
// Stay on target...
if (foundEntries.hasOwnProperty(foundEntry)) {
var singleEntry = foundEntries[foundEntry];
// Almost...there...
for( var match in singleEntry ) {
if (singleEntry.hasOwnProperty(match)) {
// Direct hit! We've drilled down to the match string itself.
var theMatch = singleEntry[match].match;
// Now, get the terms inside the strings that were referenced.
var terms = theMatch.match(/".*?"/g);
// Iterate through those strings and add them as entries in the localArray.
for( var i=0; i<terms.length; i++ ) {
var term = terms[i].replace(/"/g, '');
localArray[term] = 'xx:'+term;
stringCount++;
}
}
}
}
}
fs.writeFile( 'i18n/localize_template.json', localArray, {encoding: 'utf8'}, function(err){
console.log("File localize_template.json create successfully.");
if(err) {
throw err;
} else {
console.log("File localize_template.json create successfully.");
}
});
}
正在创建文件,但它是空白的。我尝试使用通用的Hello World! 字符串而不是localArray 进行测试,但文件仍然是空白的。
【问题讨论】:
-
您是否有适当的文件写入权限?
-
我假设在创建文件时,里面什么都没有。
-
然后我会做一些基本的故障排除 -
console.log(localArray)以查看文本是否存在,并尝试将纯文本(不是变量)写入文件以查看它是否有效。 -
@remus 是的,我已经完成了你的两个调试建议。
-
localArray验证为准确,内容仍未写入。用作参数的简单字符串"Hello World"也未写入文件。
标签: javascript node.js