在节点中使用.pipe()

dev*_*r87 0 javascript asynchronous node.js

我不清楚.pipe()函数在节点中的作用?

我怎么能用它来重构下面这两个函数中的任何一个?

exports.collectData = function(req, callback) {
    var data = "";

    req.on("data", function(chunk) {
        data += chunk;
    })

    req.on("end", function() {
        callback(data);
    })
}

http.createServer(function(req, res){
res.writeHead(200, {"Content-type": "text/plain"});
res.write("Howdy");
res.end();
}).listen(port);
Run Code Online (Sandbox Code Playgroud)

//来自答案的新代码:

var fs = require("fs");

    // Read File
    fs.createReadStream("input/people.json")
        // Write File
        .pipe(fs.createWriteStream("output/people.json"));
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 5

.pipe 将流的可读面连接到另一个流的可写面:

readable.pipe(writable)
Run Code Online (Sandbox Code Playgroud)

也就是说,这是一种将数据从一个流传递到另一个流的方法.它的节点等同于IUnix管道:

foo | bar
Run Code Online (Sandbox Code Playgroud)

我怎么能用它来重构下面这两个函数中的任何一个?

由于您似乎没有连接两个流,因此无需使用.pipe.