我有一个导入程序,应该从第三方程序上传一个特殊文件。该文件的结构如下:
TITLE,DESCRIPTION,PRICE,CURRENCY_CODE,QUANTITY,TAGS
"This is the file title","This is the file description and it can include line breaks
Size: 16x16
Weight: 1,5
for example here
more information.",12.99,USD,10,"Tag1,Tag2,Tag3"
"Next line","This is the file description and it can include line breaks
Size: 16x16
Weight: 1,5
for example here
more information.",12.99,USD,10,"Tag1,Tag2,Tag3"
"Next line","This is the file description and it can include line breaks
Size: 16x16
Weight: 1,5
for example here
more information.",12.99,USD,10,"Tag1,Tag2,Tag3"
我试图逐行读取这个文件,不幸的是这在 JS 中不起作用。
const reader = new FileReader();
reader.onload = async (evt) => {
const file = evt.target.result.split('\r\n')
当我在 Numbers (Mac = Excel) 中打开文件并通过文件 > 导出 > CSV > 文本编码 Unicode (UTF-8) 保存时,文件的输出如下:
TITLE;DESCRIPTION;PRICE;CURRENCY_CODE;QUANTITY;TAGS
"This is the file title";"This is the file description and it can include line breaks
Size: 16x16
Weight: 1,5
for example here
more information.";12.99;USD;10;"Tag1;Tag2;Tag3"
"Next line";"This is the file description and it can include line breaks
Size: 16x16
Weight: 1,5
for example here
more information.";12.99;USD;10;"Tag1;Tag2;Tag3"
"Next line";"This is the file description and it can include line breaks
Size: 16x16
Weight: 1,5
for example here
more information.";12.99;USD;10;"Tag1;Tag2;Tag3"
我可以很好地处理这种文件格式。正如我所看到的,所有列现在都通过
;
进行标记,并且换行符 evt.target.result.split('\r\n')
也可以工作。
不幸的是,我不能假设我的用户能够转换此文件。
因此,我想像 Numbers 上传文件时那样转换文件。
这是如何通过 JavaScript new FileReader() 工作的?
您可以通过两种方式处理:
安装
PapaParse
npm install papaparse
让浏览器自动转换
csv
:
let fileInput = document.getElementById('csv_file');
fileInput.addEventListener('change', function (event) {
Papa.parse(fileInput.files[0], {
download: true,
delimiter: ",",
complete: function (results) {
let csvRows = results.data;
let newCsvStr = csvRows.map(e => e.join(';')).join('\n')
console.log(newCsvStr)
}
});
});
安装
CsvWriter
npm install --save csv-parser csv-writer
在后端发送到客户端之前转换文件:
const fs = require('fs');
const csv = require('csv-parser');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const data = [];
fs.createReadStream('input.csv')
.pipe(csv({ separator: ',' }))
.on('data', (row) => {
data.push(row);
})
.on('end', () => {
let csvWriter = createCsvWriter({
path: 'output.csv',
header: Object.keys(data[0]).map(key => ({id: key, title: key}))
});
csvWriter.writeRecords(data)
.then(() => console.log('The CSV file was written successfully'));
});