LoginSignup
4
3

More than 5 years have passed since last update.

プロセス終了時のファイル出力

Last updated at Posted at 2015-03-16

プロセス終了結果を待って,
ファイル出力をしてようとチャレンジした.

イレギュラーかもしれないので,参考にならないかも.

結果はファイルは生成されるが,ファイルに書き込みはできないでした.

環境

  • Node.js v0.10.36
exitProcessFileWrite.js
var fs = require('fs');
console.log('Write file test');

function write(filename, s) {
  fs.writeFile('test.txt', s, function(error) {
  if(error) {
    console.log('ERROR', error);
  }
 console.log('DONE');
 });
}

// ファイル生成できるし,書き込みもできる.
write('OnProcessing.txt', 'On processing can write file');

process.on('exit', function(code) {
  // ファイルは生成するが,書き込みができない
  write('OnProcessExit.txt''On process exit cannot write file');
}); 

ドキュメントの記述

困ったときは公式doc.
Event: 'exit'

イベントループを抜ける直前はファイル出力は受け付けないのだろうか?
process.on('exit'...)の中でfsモジュールは生存してたみたいですが.

Event: 'exit'#
プロセスが終了しようとしている時に生成されます。 この位置からイベントループを抜けることを防ぐ方法はなく、全ての 'exit' リスナーの実行が完了すると、プロセスは終了します。 従って、このハンドラでできることは 同期 操作 だけ です。 これは (ユニットテストのように) モジュールの状態をチェックするのに適した フックとなります。 コールバックはプロセスの終了コードを唯一の引数として呼び出されます。

exit を監視する例:

process.on('exit', function(code) {
// do NOT do this
setTimeout(function() {
console.log('This will not run');
}, 0);
console.log('About to exit with code:', code);
});

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3