读取 csv 文件
let index = url.parse(urlStr, true).query.index
// 同步读取
const content = fs.readFileSync(filePath)
读取的文件转 json,导入 csvtojson
库,安装指令 npm install csvtojson
const csv = require('csvtojson')
const converter = csv()
.fromFile(filePath)
.then((arr) => {
});
异步读取文件
const content = fs.readFileSync(filePath)
const converter = csv()
.fromFile(filePath)
.then((arr) => {
});
csv 例子如下
name, age, gender, height
jom,12,male,180
halo, 23, female,170
解析后得到
[{"name": "jom", "age": 12, "gender": "male", "height": 180},
{"name": "halo", "age": 23, "gender": "female", "height": 170}]
之后对数组进行删除
delete arr[index]
json 转 csv,导入 json2csv
库,并写入文件
var json2csv = require('json2csv').parse;
try {
var result = json2csv(arr);
fs.writeFileSync(filePath, result);
} catch (err) {
console.error("convert", err, err.stack);
}
网友评论