美文网首页
Node.js - 读取 CSV 文件并对其文件进行增删查

Node.js - 读取 CSV 文件并对其文件进行增删查

作者: ienos | 来源:发表于2023-05-15 20:36 被阅读0次

    读取 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);
        }
    

    相关文章

      网友评论

          本文标题:Node.js - 读取 CSV 文件并对其文件进行增删查

          本文链接:https://www.haomeiwen.com/subject/auhvsdtx.html