Node.js 方法不返回任何响应,挂起请求

Node.js method does not return any response, pending request

本文关键字:响应 挂起 请求 任何 返回 js 方法 Node      更新时间:2023-09-26

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

知道为什么此方法不返回任何响应吗?

您正在使用 readFile ,它也是异步的,工作原理如下:

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

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

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

分别检查文档中的readFilewriteFile