синхронное преобразование нескольких файлов csv в json в nodejs
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 загрузки принимает в качестве входных данных несколько файлов. также он преобразован из csv в json с использованием пакетов fs и csvjson.
1 ответ
Решение
Вы выполняете вызов стиля обратного вызова внутри цикла for, который не работает, вы ожидаете, что он сработает. Вам нужно обернуть это обещанием или использовать обещанную версию fs. Что-то вроде этого
const fs = require("fs").promises;
exports.upload = async (req, res) => {
if (!req.files) {
ResponseHandler.notFound(res, ERROR.ALL_FIELD_REQUIRED);
}
const files = req.files;
for (const file of files) {
const csvFilePath = file.path;
// eslint-disable-next-line no-loop-func
const fileContent = await fs.readFile(csvFilePath, "utf-8");
const options = {
"delimiter": ",",
"quote": "\""
};
// eslint-disable-next-line complexity
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);
// eslint-disable-next-line no-catch-shadow
} catch (err) {
return ResponseHandler.internalServerError(
res,
ERROR.INTERNAL_SERVER_ERROR
);
}
}
return ResponseHandler.send(res, STATUS.SUCCESS, SUCCESS.FILE_UPLOADED);
};
Надеюсь это поможет. Возможно, вам придется кое-что изменить здесь или там, но вы поймете идею.