【问题标题】:node - fs.writeFile creates a blank filenode - fs.writeFile 创建一个空白文件
【发布时间】: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


【解决方案1】:

到 2020 年,在 async 函数中,使用 await,如下所示:

try {
    // blah blah


    // Write data to the file
    await fs.writeFile(path, data, function (err) {
        if (err) {
            console.error(`An error occurred while writing data to the file: ${err.message}`)
            throw err
        }
    })

    // blah blah
}
catch(err) {
    console.error(`An error occurred while writing data to the file: ${err.message}`)
}

【讨论】:

  • 您为什么要await 一个函数并将错误处理程序回调传递给它?
【解决方案2】:

尝试找出您的代码是否有

process.exit()

出于某种原因,我有一个温和的仅供测试。如果你这样做了,把这个注释掉,你会很高兴的。我的版本是v8.6.0。

【讨论】:

    【解决方案3】:

    你需要使用同步版本:

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

    【讨论】:

    • 你能解释一下为什么异步方法不起作用吗?
    【解决方案4】:

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

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

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

    【讨论】:

    • 我发现使用.writeFileSync 更早。 localArray 周围的 ** 有什么作用?
    • 这只是这个站点中的粗体符号,但它不适用于代码 sn-p:) 只是为了看看在哪里进行更改。很高兴它成功了。
    【解决方案5】:

    为了更清楚地回答,fs.writeFile 是异步的,顶级 grunt 的东西不知道等待由onComplete 启动的异步操作。你需要弄清楚如何告诉 grunt 你有一个未完成的异步操作,this is a feature that grunt-search doesn’t support 除外。否则,当您从onComplete 返回时,grunt-search 将立即将任务标记为已完成,并且 grunt 将退出导致节点进程在异步写入完成之前退出。

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

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

    【讨论】:

      猜你喜欢
      • 2017-12-21
      • 1970-01-01
      • 2020-01-04
      • 2015-09-02
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 2018-03-08
      • 1970-01-01
      相关资源
      最近更新 更多