admin管理员组文章数量:1391964
I'd like my server to save some essential data when node exits and load them next time.
I tried what the answer of this question suggested, but the server seems to close before it is able to write to the file.
This is the exact code I am trying:
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}));
I'd like my server to save some essential data when node exits and load them next time.
I tried what the answer of this question suggested, but the server seems to close before it is able to write to the file.
This is the exact code I am trying:
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}));
Share
Improve this question
edited May 23, 2017 at 10:26
CommunityBot
11 silver badge
asked Jun 11, 2015 at 12:01
user3262713user3262713
3799 silver badges21 bronze badges
1 Answer
Reset to default 7I think if you tried fs.writeFileSync
it would solve this.
https://nodejs/api/fs.html#fs_fs_writefilesync_filename_data_options
The code would then be:
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
}
The issue I believe is because of the async nature. By using the synchronous version of writeFile you're forcing the process to finish executing everything before exiting.
本文标签: javascriptWriting to a txt file before nodejs exitsStack Overflow
版权声明:本文标题:javascript - Writing to a .txt file before node.js exits - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744632180a2616608.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论