Node.js方法不返回任何响应,待处理请求

时间:2013-09-17 11:02:17

标签: javascript node.js express

使用node.js + express.js的简单上传方法:

upload: function(req, res, next){
    //go over each uploaded file
    async.each(req.files.upload, function(file, cb) {
        async.auto({
            //create new path and new unique filename
            metadata: function(cb){
                //some code...
               cb(null, {uuid:uuid, newFileName:newFileName, newPath:newPath});
            },
            //read file
            readFile: function(cb, r){
               fs.readFile(file.path, cb);
            },
            //write file to new destination
            writeFile: ['readFile', 'metadata', function(cb,r){
                fs.writeFile(r.metadata.newPath, r.readFile, function(){
                    console.log('finished');
                });   
            }]
        }, function(err, res){
            cb(err, res);
        });
    }, function(err){
        res.json({success:true});
    });

   return;
}

该方法迭代每个上传的文件,创建一个新文件名并将其写入元数据中设置的给定位置。

console.log('finished');
写入完成时会触发

,但客户端永远不会收到响应。 2分钟后,请求被预定,但文件已上传。

为什么这个方法没有返回任何响应的任何想法?

1 个答案:

答案 0 :(得分:1)

您正在使用readFile,这也是异步的,并且工作方式如下:

fs.readFile('/path/to/file',function(e,data)
{
    if (e)
    {
        throw e;
    }
    console.log(data);//file contents as Buffer
});

我可以在这里传递一个函数的引用来处理这个问题,但IMO,简单地使用readFileSync会更容易,它直接返回Buffer,并且可以传递给{ {1}}没有问题:

writeFile

分别查看readFilewriteFile的文档

相关问题