【问题标题】:Writing to a .txt file before node.js exits在 node.js 退出之前写入 .txt 文件
【发布时间】:2015-08-27 02:45:09
【问题描述】:

我希望我的服务器在节点退出时保存一些基本数据并在下次加载它们。

我尝试了this question 建议的答案,但服务器似乎在能够写入文件之前关闭。

这是我正在尝试的确切代码:

process.stdin.resume();

function exitHandler(options, err) {
    if(!serverUp){return;}
    serverUp = false;
    fs.writeFile('server.txt', String(search_index),function (err) {
        console.log("debug") // <-- This doesn't happen
        process.exit();
    });   
}

//do something when app is closing
process.on('exit', exitHandler.bind(null,{cleanup:true}));

//catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, {exit:true}));

//catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {exit:true}));

【问题讨论】:

    标签: javascript node.js text exit writefile


    【解决方案1】:

    我想如果你尝试fs.writeFileSync 会解决这个问题。

    https://nodejs.org/api/fs.html#fs_fs_writefilesync_filename_data_options

    代码将是:

    function exitHandler(options, err) {
        if(!serverUp){return;}
        serverUp = false;
        fs.writeFileSync('server.txt', String(search_index));
        console.log("debug");
        process.exit();   // Don't think you'll need this line any more
    }
    

    我认为这个问题是由于异步性质造成的。通过使用 writeFile 的同步版本,您会强制进程在退出之前完成所有操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 2016-01-29
      • 2015-11-22
      • 2018-07-02
      • 1970-01-01
      相关资源
      最近更新 更多