javascript 节点 - fs.writeFile 创建一个空白文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31572484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:00:00  来源:igfitidea点击:

node - fs.writeFile creates a blank file

javascriptnode.js

提问by Plummer

I'm trying to write a new file inside a grunt-search callback.

我正在尝试在 grunt-search 回调中编写一个新文件。

The process takes and object, traverses through it for some data, creates a new array, and then writes that array to a JSON file. The writing part isn't working out so well...

该过程获取和对象,遍历它获取一些数据,创建一个新数组,然后将该数组写入 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.");
        }
    });    
}

The file is being created, but it's blank. I've tried using a generic Hello World!string instead of localArrayto test, but the file is still blank.

正在创建文件,但它是空白的。我尝试使用通用Hello World!字符串而不是localArray进行测试,但该文件仍然是空白的。

回答by Lacho Tomov

You need to use the synchronous version:

您需要使用同步版本:

fs.writeFileSync("./output.txt", "file contents"); 

回答by binki

To answer more clearly, fs.writeFileis asynchronous and the top level grunt stuff doesn't know to wait for asynchronous operations started by onComplete. You need to figure out how to tell grunt that you have an unfinished asynchronous operation, except this is a feature that grunt-searchdoesn't support. Otherwise, when you return from onComplete, grunt-searchwill mark the task as done immediately and grunt will exit causing the node process to exit before the asynchronous write completes.

更清楚地回答,fs.writeFile是异步的,顶级 grunt 的东西不知道等待由onComplete. 您需要弄清楚如何告诉 grunt 您有一个未完成的异步操作,除非这是一个grunt-search不支持. 否则,当您从 返回时onCompletegrunt-search将立即将任务标记为完成,并且 grunt 将退出,导致节点进程在异步写入完成之前退出。

Another thought is to use grunt.file.write(). This is a synchronous API, so it won't require you solve the problem of being unable to tell grunt that your task isn't done. Also, using this API will make your code magically support grunt's --no-writeoption by being a no-op when the user requests a dry run.

另一个想法是使用grunt.file.write(). 这是一个同步 API,所以它不需要你解决无法告诉 grunt 你的任务没有完成的问题。此外,--no-write当用户请求试运行时,使用此 API 将使您的代码神奇地支持 grunt 的选项,因为它是空操作。

onComplete: function (matches) {
    grunt.file.write('test', JSON.stringify(matches));
},

回答by Ibio Tan

Try to find out if your code has

尝试找出您的代码是否具有

process.exit()

进程.退出()

For some reason, I have one temperately for testing only. If you do, comment out this one and you will be good to go. My version is v8.6.0.

出于某种原因,我有一个仅供测试的温和版本。如果你这样做了,注释掉这个,你就可以开始了。我的版本是 v8.6.0。

回答by AlexP

Your problem should be that the fs.writeFile starts "asynchronous". Try to change the localArray in here (hardcode it to see if it works):

您的问题应该是 fs.writeFile 开始“异步”。尝试更改此处的 localArray(对其进行硬编码以查看它是否有效):

fs.writeFile( 'i18n/localize_template.json', localArray, callback)

And there it should work. The solution i think it is that you should use fs.writeFileSync, or to initialize the localArray outside the oncomplete function, before it starts.

它应该在那里工作。我认为的解决方案是您应该使用 fs.writeFileSync,或者在 oncomplete 函数之外初始化 localArray,然后再启动。