循环中的nodejs fs.rename(如何正确使用Promise)

时间:2018-09-22 21:06:14

标签: node.js

我知道我的以下代码将最终出现在“文件上传未成功”中,因为由于fs.rename()的异步行为,successAmount = successAmount + 1无法正常工作...很显然,在此处使用promises但我不知道如何以更好的方式来组织代码。 我的目标是在重命名所有文件时发送状态200。 您可以帮助我正确重构代码,我想Promise.All()应该可以解决它,但是我不知道怎么办?

myMultiFileUploader: async (req, res, next) => {
    console.log('Entering myMultiFileUploader');

    var successAmount = 0;

    for (let fileItem of req.files) {

        console.log('File '+fileItem);
        console.log('Filename '+fileItem.filename);
        console.log('Mimetype '+fileItem.mimetype);
        console.log('Orig Name '+fileItem.originalname);

        //rename files
        var oldName =""+process.env.FILEUPLOAD_FOLDER+""+fileItem.filename;
        var newName = ""+process.env.FILEUPLOAD_FOLDER+""+fileItem.originalname;

        fs.rename(oldName, newName, function (err) {
            if (err) {
                console.log("Could not rename uploaded file oldname "+oldName+" to newname "+newName);
            }
            fs.stat(newName, function (err, stats) {
            if (err) {
                console.log("Could not rename uploaded file");
            }
            else{
                successAmount = successAmount+1;
            }
            });
        });
    } 

    if(successAmount===req.files.length-1){
        return res.status(200).json({success: 'All Files have been successfully uploaded.'});
    }else{
        return res.status(401).json({error: 'Upload of files was not successful.'});
    }   

}

1 个答案:

答案 0 :(得分:2)

我使用了异步/等待,所以不必要的回调已被删除。如果有任何文件显示错误,它将被发送以进行捕获,因此不需要successAmount计数。我已在下面附上了更新的代码。希望对您有所帮助。

const util = require('util');
const stat = util.promisify(fs.stat);
const rename = util.promisify(fs.rename);

myMultiFileUploader: async (req, res, next) => {
    try {
        console.log('Entering myMultiFileUploader');

        await req.files.map( async (fileItem, index) => {

            console.log('File '+fileItem);
            console.log('Filename '+fileItem.filename);
            console.log('Mimetype '+fileItem.mimetype);
            console.log('Orig Name '+fileItem.originalname);

            //rename files
            var oldName =""+process.env.FILEUPLOAD_FOLDER+""+fileItem.filename;
            var newName = ""+process.env.FILEUPLOAD_FOLDER+""+fileItem.originalname;

            await rename(oldName, newName);
            await stat(newName);
        })
        return res.json({success: 'All Files have been successfully uploaded.'});   
    }
    catch (err) {
        console.log('Error Occured : '+ err);
        res.status(401).json({error: 'Upload of files was not successful.'});
    }
}