Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 处理传入post请求时,nodejs中的管道和uppipe_Node.js - Fatal编程技术网

Node.js 处理传入post请求时,nodejs中的管道和uppipe

Node.js 处理传入post请求时,nodejs中的管道和uppipe,node.js,Node.js,考虑以下代码,使用nodejs 0.10.22和expressjs 3.x app.post('/upload', function(req,res){ var size = 0; var writable = fs.createWriteStream('./example.file'); req.pipe(writable); req.on('data', function(data){ size += data.length;

考虑以下代码,使用nodejs 0.10.22和expressjs 3.x

app.post('/upload', function(req,res){

    var size = 0;
    var writable = fs.createWriteStream('./example.file');

    req.pipe(writable);
    req.on('data', function(data){
        size += data.length;
        if (size > 1048576) {
            req.unpipe();
            //writable = null;
        }
    })

    res.send('end');
});
当用户上传一些数据(例如文件)时,会创建一个WriteStream来保存数据

为了限制保存到硬盘的数据量,我有一个“数据”侦听器。当大小>1 Mb时,我调用req.unpipe()停止管道

但是,req将管道传输到可写文件中,最后,example.file将与上载的文件一样大。即使我通过调用writeable=null使writeable为空,req.pipe()仍会将所有数据管道传输到example.file


我的代码有问题吗?或者这是stream.readable.pipe()方法的错误吗?

如果您正在使用express.bodyParser()的话,请尝试将您的“/upload”路径放在它前面。

检查了您的代码,它似乎可以工作。您正在测试的文件的大小小于1114112吗?我认为代码可以工作,但事实并非如此。我尝试了一个2MB的文件和一个10MB的文件。忘了提到,我使用的是windows 7I,我没有使用express.bodyParser(),因为bodyParser()中的多部分()将在下一版本的connect中逐步淘汰。我试图以最少的抽象理解nodejs。顺便说一句,即使我使用:http.createServer(function(req,res){/*piping code here*/}),当大小>1MB时,req.pipe()仍然保持管道