Plu*_*mer 6 javascript node.js
我正在尝试在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.");
}
});
}
Run Code Online (Sandbox Code Playgroud)
正在创建该文件,但它是空白的.我尝试使用通用Hello World!字符串而不是localArray测试,但文件仍然是空白的.
您需要使用同步版本:
fs.writeFileSync("./output.txt", "file contents");
Run Code Online (Sandbox Code Playgroud)
为了更清楚地回答,fs.writeFile是异步的,顶级的grunt东西不知道等待启动的异步操作onComplete.你需要弄清楚如何告诉grunt你有一个未完成的异步操作,除了这是一个grunt-search不支持的功能.否则,当您从中返回时onComplete,grunt-search将立即将任务标记为已完成,并且grunt将退出,导致节点进程在异步写入完成之前退出.
另一种想法是使用grunt.file.write().这是一个同步API,所以它不需要你解决无法告诉grunt你的任务没有完成的问题.此外,--no-write当用户请求干运行时,使用此API将使您的代码通过无操作来神奇地支持grunt的选项.
onComplete: function (matches) {
grunt.file.write('test', JSON.stringify(matches));
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9803 次 |
| 最近记录: |