我需要从客户端(nodejs命令行)和服务器(表达nodejs)流式传输文件. 这是客户端: var request = require('request');var fs = require('fs');// ... var readStream = fs.createReadStream(file.path); readStream.on('end', func
这是客户端:
var request = require('request'); var fs = require('fs'); // ... var readStream = fs.createReadStream(file.path); readStream.on('end', function() { that.emit('finished'); }); readStream.pipe(request.post(target)); // ...
这是服务器端:
var fs = require('fs'); var path = require('path'); // ... app.post('/:filename', function(req, res) { req.setEncoding('binary'); var filename = path.basename(req.params.filename); filename = path.resolve(destinationDir, filename); var dst = fs.createWriteStream(filename); req.pipe(dst); req.on('end', function() { res.send(200); }); }); // ...
一切正常,文件在服务器端正确保存……但它们比源文件大50%左右.我试图看到两个文件与hexdump之间的区别,服务器端文件有相似的内容,但有时为0xC2.我想这与编码有关.
不要调用req.setEncoding(‘binary’).这将是convert every single chunk into strings,主要用于从流中读取字符串.当您将请求直接传递给文件时,您不需要这样做.