exports.upload = async (req, res) => {
if (!req.files) {
ResponseHandler.notFound(res, ERROR.ALL_FIELD_REQUIRED);
}
const files = req.files;
for(let file of files){
const csvFilePath = file.path;
fs.readFile(csvFilePath, 'utf-8', async (err, fileContent) => {
if (err) {
return ResponseHandler.internalServerError(
res,
ERROR.INTERNAL_SERVER_ERROR
);
}
const options = {
delimiter: ',',
quote: '"'
};
const jsonObj = csvjson.toObject(fileContent, options).map(element => {
return {
guid: element.guid || null,
name: element.name || null,
whenChanged: element.whenChanged || null,
whenCreated: element.whenCreated || null,
co: element.co || null,
company: element.company || null,
givenName: element.givenName || null,
sn: element.sn || null,
profileImage: element.profileImage || null,
designation: element.designation || null,
jobTitle: element.jobTitle || null,
department: element.department || null,
ward: element.ward || null,
site: element.site || null,
region: element.region || null,
offer: element.offer || null,
isAppUser: element.isAppUser || null
};
});
try {
await UserService.createUsers(jsonObj);
} catch (err) {
return ResponseHandler.internalServerError(
res,
ERROR.INTERNAL_SERVER_ERROR
);
}
});
}
return ResponseHandler.send(res, STATUS.SUCCESS, SUCCESS.FILE_UPLOADED);
};
我在同步执行代码时遇到问题,应该先执行 for 循环,然后再给出响应。如果可能,请为我提供使用 async/await 的解决方案。此上传 api 将多个文件作为输入。还使用 fs 和 csvjson 包将其从 csv 转换为 json。