LoginSignup
1
2

More than 5 years have passed since last update.

nodejsのファイルシステムで迷った

Last updated at Posted at 2015-11-20

環境

  • Node.js 5.1

概要

Node.jsのコアモジュールのfsモジュールを使って、getリクエストのresponseを非同期で保存して終わったら何か表示するプログラムを作った時。

問題

var outfile = fs.createWriteStream(savepath);
http.get(url, (res) => {
  res.pipe(outfile, { end: false});
  res.on('end', () => {
    outfile.close();
    console.log("ok");
  });
});

これはソースの一部ですが、実行すると途中までファイルに書き込まれて最後まで書き込まれずに終了することが有りました。

対処

stream.writableを終了する時はendメソッドを使う。

どうやらcloseメソッドを利用するとファイルが書き込み中だったとしても強制的にクローズする模様。
endにするとfinishイベントが発火されるまで待ってくれる。

参考
https://nodejs.org/api/stream.html#stream_class_stream_writable

1
2
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
1
2