在node.js退出之前写入.txt文件

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

我试着回答这个问题的build议,但服务器似乎closures,才能写入文件。

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

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})); 

我想如果你尝试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 } 

我相信这个问题是由于asynchronous的本质。 通过使用writeFile的同步版本,你迫使进程在退出之前完成所有的事情。