0

使用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 分钟后,请求被取消,但文件已上传。

任何想法为什么此方法不返回任何响应?

4

1 回答 1

1

您正在使用readFile,它也是异步的,并且像这样工作:

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

我可以在这里传递对函数的引用来处理这个问题,但是 IMO,简单地使用它会更容易readFileSync,它直接返回 Buffer ,并且可以writeFile毫无问题地传递给:

fs.writeFile(r.metadata.newPath, r.readFileSync, function(err)
{
    if (err)
    {
        throw err;
    }
    console.log('Finished');
});

检查文档readFilewriteFile分别

于 2013-09-17T11:22:54.790 回答