我有一个类似的请求要处理CSV文件,我尝试实现了您的解决方案:只要我在console log中使用它,它就可以工作。我尝试将“record”变量存储在一个名为“results”的数组中,但我只得到了一个空数组[],并在呈现此空数组后接收了console.log响应,呈现解析的CSV数据。
所以这似乎是同步问题...我的意思是,处理CSV文件需要一段时间。因此,我尝试压缩您的代码,并将其转换为Promise,然后执行它。因此,在Promise执行之后,我的数组已经准备好使用了。
- 注意:我是初学者,因此可能包含一些错误。到目前为止,它对我来说运行良好。
- 注意:我的CSV测试文件的内容是:
title, type, value, category
Loan, income, 1500, Others
Website Hosting, outcome, 50, Others
Ice cream, outcome, 3, Food
注意:与您的情况有一些不同:我从路由'/import'接收一个单个文件。我使用Insomnina Designer应用程序发送一个名为importFile的多部分表单体文件。
注意:我导入了您使用的相同库,并且我也使用了中间件的概念。
注意:在这种情况下,我只期望一个文件,因此我使用multer({dest: './upload'}).single('importFile')。也可以使用.any()。
注意:我正在使用typescript,因此对于JS来说,只需要在某些变量声明之后删除:@type,例如
注意:我留下了选项1-仅使用数组和选项2-使用对象。
const results: object[] = [];
becomes:
const results = [];
让我们来看代码:
import { Router, Request, Response } from 'express';
import csv from 'csv-parse';
import multer from 'multer';
import fs from 'fs';
interface CSVTransactionDTO {
title: string;
value: number;
type: 'income' | 'outcome';
category: string;
}
app.post(
'/import',
multer({ dest: './upload' }).single('importFile'),
async (request: Request, response: Response) => {
const filePath = request.file.path;
let rowCounter = 0;
const results: string[] = [];
const newTransactions: CSVTransactionDTO[] = [];
function parseCSVPromise(): Promise<void> {
return new Promise((resolve, reject) => {
const ConfigCSV = {
from_line: 2,
trim: true,
};
fs.createReadStream(filePath)
.pipe(csv(ConfigCSV))
.on('data', row => {
rowCounter += 1;
results.push(row);
const [title, type, value, category] = row;
newTransactions.push({title, type, value, category});
})
.on('error', error => {
reject(error);
throw new Error('Fail to process CSV file');
})
.on('end', () => {
resolve();
});
});
}
await parseCSVPromise();
console.log('option1', results);
console.log('option2',newTransactions);
return response.json({ resultsCounter, results });
选项1的响应:
[
[ 'Loan', 'income', '1500', 'Others' ],
[ 'Website Hosting', 'outcome', '50', 'Others' ],
[ 'Ice cream', 'outcome', '3', 'Food' ]
]
选项2的响应:
[
{ title: 'Loan', type: 'income', value: '1500', category: 'Others' },
{ title: 'Website Hosting', type: 'outcome', value: '50', category: 'Others' },
{ title: 'Ice cream', type: 'outcome', value: '3', category: 'Food' }
]