2016-03-30 2 views
2

の終了前に呼び出され、私は、次のミドルウェア機能ノード(express.js)は、ストリーム

var bodyParser = require('body-parser'), 
    fs = require('fs'); 
module.exports = function(req, res, next) { 
    // Add paths to this array to allow binary uploads 
    var pathsAllowingBinaryBody = [ 
    '/api2/information/upload', 
    '/api2/kpi/upload', 
    ]; 

    if (pathsAllowingBinaryBody.indexOf(req._parsedUrl.pathname) !== -1) { 
    var date = new Date(); 
    req.filePath = "uploads/" + date.getTime() + "_" + date.getMilliseconds() + "_" + Math.floor(Math.random() * 1000000000) + "_" + parseInt(req.headers['content-length']); 

    var writeStream = fs.createWriteStream(req.filePath); 
    req.on('data', function(chunk) { 
     writeStream.write(chunk); 
    }); 
    req.on('end', function() { 
     writeStream.end(); 
     next(); 
    }); 
    } else { 
    bodyParser.json()(req, res, next); 
    } 
}; 

ファイルが正しく転送されているいるが、悲しいことに

req.on('end', function() { 
    writeStream.end(); 
    next(); 
}); 

next()すべてのデータを新しいファイルに書き込む前に呼び出されます。

私の質問は何ですか?そして私はそれをどのように修正できますか?

答えて

4

書き込み可能ファイルストリームのcloseイベントを使用して、ファイル記述子がいつ閉じられたかを知ることができます。

これを置き換えます。これで

var writeStream = fs.createWriteStream(req.filePath); 
req.on('data', function(chunk) { 
    writeStream.write(chunk); 
}); 
req.on('end', function() { 
    writeStream.end(); 
    next(); 
}); 

を:

req.pipe(fs.createWriteStream(req.filePath)).on('close', next); 
+0

うわー。それは簡単でした!どうもありがとうございます! –

+0

私は自分の答えを更新しました。技術的には 'close'イベントでなければなりません。これは' fs'モジュールからのファイルストリームが使う特別なイベントです。 – mscdex

関連する問題