在nodejs中读取csv并为每一行创建新文件

时间:2018-04-12 21:09:08

标签: javascript node.js

我需要读取CSV文件,遍历每一行,创建该行的新文件并删除该行。到目前为止,我已经这样做了

    var fs = require("fs"); // module
    var glob = require("glob");// helps to find file from globally using path
    var path = require("path");

    glob.sync(path.join(__dirname, "Database.csv")).forEach(function(csv_filename) {
    if (!(/_new\.csv$/.test(csv_filename))) {
    fs.readFile(csv_filename, "utf8", function(err, data) {
        if (err){ // if there is some mistakes
            console.log(err)
        }else{
            let stringTotal="";
            var arrayEachLines = data.split("\n");
          /*  arrayEachLines.forEach(function(line){    
            stringTotal=stringTotal+line+"\n";
                            */
            var o={};

            var i;
            var row;
                for (i=0; i<arrayEachLines.length; i++){
                o[i]=arrayEachLines[i];
                o[i]=o[i].replace(o[row],"");

            }
            arrayEachLines.push(o);

            console.log(o);


            fs.writeFile(csv_filename.replace(/Excel\.csv_original/, "Excel.csv_updated").replace(/\.csv$/, "_new.csv"), o[i], "utf8", function(err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log(csv_filename + " converted");
                }
            });
        }

    });
}});

数据库csv包含

  a,"""blue""",11,3
  ba,"""blue""",2,4
  c,"""blue""",0,5

我希望系统读取第一行,使用第一行字段创建新文件,删除行并读取第二行执行相同操作 任何建议都将受到高度赞赏的人

谢谢

1 个答案:

答案 0 :(得分:0)

创建一个事件流,使用event-stream发出每一行并写入新的csv文件。这样就可以了解

const fs = require('fs');
const es = require('event-stream');
const path = require("path");

let lineCount = 0;
let csvPath = path.join(__dirname, "Database.csv");
fs.createReadStream(csvPath)
    .pipe(es.split())
    .pipe(es.mapSync((line) => {
        lineCount += 1;
        let filePath = path.join(__dirname, `line${lineCount}.csv`)
        fs.writeFileSync(filePath , line);
    }).on('error', (err) => {
        console.log('Error while reading file.', err);
    }).on('end', () => {
        console.log('Read entire file.')
    }));