简体   繁体   中英

Why doesn't piping work inside a callback

I have the following server:

http.createServer(function (req, res) {

  fs.mkdir(__dirname + '/output', function (err) {

    req.pipe(fs.createWriteStream(__dirname + '/output/file.txt'));
    res.end();

  });

}).listen(3000);

I am then using request to pipe a stream to the server.

var fs = require('fs');
var request = require('request');

var crs = fs.createReadStream(__dirname + '/file.txt');
var r = request.post('http://0.0.0.0:3000');

crs.pipe(r);

Sometimes it works but most of the time /output/file.txt is empty. When I move the req.pipe(...) outside of the mkdir callback it works every time. Could anybody explain why it is happening?

Since mkdir is asynchronous, the data in the request is emitted while the directory is being created. You need to instruct the stream to not emit the data until later by using pause and resume .

http.createServer(function (req, res) {
  req.pause();
  fs.mkdir(__dirname + '/output', function (err) {
    req.pipe(fs.createWriteStream(__dirname + '/output/file.txt'));

    req.resume();
    res.end();
  });
}).listen(3000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM