I was trying to convert files from XLSX to CSV on the server, but when I make a post request on Postman, I get "Error importing users".
I am using this package to convert XLSX to CSV: https://www.npmjs.com/package/xlsx.
I tried the solution from: Convert XLS to CSV on the server in Node
Below is the function to import the file:
exports.importFromCSV = async function importFromCSV(req, res) {
try {
if (!req.user || !req.user.isRoot) throw new Error('Allowed only for Admin');
if (!req.file) throw new Error('No file supplied');
const csvString = await new Promise((resolve, reject) => {
const workBook = XLSX.readFile(csvRows);
XLSX.writeFile(workBook, userdata, { bookType: "csv" })
fs.readFile(req.file.path, {encoding: 'utf-8'}, (err, data) => {
if (err) return reject(err);
resolve(data.toString());
});
});
const csvRows = await promisify(csvParse)(csvString, {columns: true});
const rows = csvRows.map(row => {
const name = (row.name || '').split(/\s+/)[0].trim();
const lastname = (row.lastname || '').trim();
const username = `${_.snakeCase(name)}_${_.snakeCase(lastname)}`;
const password = (row.password || '').trim();
const invalid = [name, lastname, password, username].filter(e => !e).length;
return {
value: row,
user: new User({
name,
lastname,
username,
password,
groups: [],
favoriteFiles: [],
payingStatus: false,
isRoot: false
}),
invalid,
};
});
Does anyone have any idea what is wrong with the code? Thanks in advance!