如何在nodejs json2csv中的现有csv文件中追加新行?

时间:2016-11-21 17:27:23

标签: javascript json node.js csv npm-install

我想在现有的csv文件中添加新行?如果存在csv文件,那么我不想添加列标题,只想在文件中存在行之后添加新行。

以下是我正在尝试的代码:

var fields = ['total', 'results[0].name.val'];
var fieldNames = ['Total', 'Name'];

var opts1 = {
  data: data,
  fields: fields,
  fieldNames: fieldNames,
  newLine: '\r\n'

};

var opts2 = {
  newLine: '\r\n',
  data: data,
  fields: fields,
  fieldNames: fieldNames,
  hasCSVColumnTitle: false,

};

fs.stat('file.csv', function (err, stat) {
  if (err == null) {
    console.log('File exists');
    var csv = json2csv(opts2);
    fs.appendFile('file.csv', csv, function (err) {
      if (err) throw err;
      console.log('The "data to append" was appended to file!');
    });
  } else if (err.code == 'ENOENT') {
    // file does not exist
    var csv = json2csv(opts1);
    fs.writeFile('file.csv', csv, function (err) {
      if (err) throw err;
      console.log('file saved');
    });
  } else {
    console.log('Some other error: ', err.code);
  }
});

5 个答案:

答案 0 :(得分:10)

以下代码将按您的要求执行:

  1. 第一次运行时 - 会写标题
  2. 之后的每次运行 - 将json数据附加到csv文件

    var fs = require('fs');
    var json2csv = require('json2csv');
    var newLine= "\r\n";
    
    var fields = ['Total', 'Name'];
    
    var appendThis = [
        {
            'Total': '100',
            'Name': 'myName1'
        },
        {
            'Total': '200',
            'Name': 'myName2'
        }
    ];
    
    var toCsv = {
        data: appendThis,
        fields: fields,
        hasCSVColumnTitle: false
    };
    
    fs.stat('file.csv', function (err, stat) {
        if (err == null) {
            console.log('File exists');
    
            //write the actual data and end with newline
            var csv = json2csv(toCsv) + newLine;
    
            fs.appendFile('file.csv', csv, function (err) {
                if (err) throw err;
                console.log('The "data to append" was appended to file!');
            });
        }
        else {
            //write the headers and newline
            console.log('New file, just writing headers');
            fields= (fields + newLine);
    
            fs.writeFile('file.csv', fields, function (err, stat) {
                if (err) throw err;
                console.log('file saved');
            });
        }
    });
    

答案 1 :(得分:2)

我对函数的行为进行了一些更改,现在我用2种方法验证是否有标题,如果存在,我将忽略它并添加行,如果没有,则添加标题,从对象中删除引号并传递一些等待,因为该函数是同步的,没有等待,所以异步是没有意义的哈哈哈

传递给filename的CSV值是节点将在项目根目录中查找以保存最终文档的文件夹的名称

??

Fiz umasmudançasem como afunçãose comporta,agora eu valido com 2个存在的cabeçalho,这些存在的euignoro ele e adiciono成行,senãoeu adiciono ocabeçalho,移除aspas dos objetos porque afunçãoage sync enãotinha nenhum awaitentãonãofazia sentido ser async haha​​ha

Oval CSV passado参数或命令的最终面目是什么?

const fs = require("fs");
const path = require("path");
const json2csv = require("json2csv").parse;

// Constructor method to assist our ReadFileSync
const readFileSync = filePath =>
  fs.readFileSync(filePath, { encoding: "utf-8" });

// A helper to search for values ​​in files =D
const findWord = async (text, filePath) => {
  const result = await readFileSync(path.join(__dirname, filePath));
  return Promise.resolve(RegExp("\\b" + text + "\\b").test(result));
};

const write = async (fileName, fields, data) => {
  // output file in the same folder
  const filename = path.join(__dirname, "CSV", `${fileName}`);
  let rows;

  // I check if there is a header with these items
  const hasValue = await findWord("Name,Position,Salary", "./CSV/test.csv");
//  If there is a header I add the other lines without it if I don't follow the natural flow
  if (hasValue) {
    rows = json2csv(data, { header: false });
  } else if (!fs.existsSync(fields)) {
  // If file doesn't exist, we will create new file and add rows with headers.
    rows = json2csv(data, { header: true });
  } else {
    // Rows without headers.
    rows = json2csv(data, { header: false });
  }

  // I deal with the information by removing the quotes
  const newRows = rows.replace(/[\\"]/g, "");
  // Append file function can create new file too.
  await fs.appendFileSync(filename, newRows);
  // Always add new line if file already exists.
  await fs.appendFileSync(filename, "\r\n");
};

fields = ["Name", "Position", "Salary"];
data = [
  {
    Name: "Test1",
    Position: "Manager",
    Salary: "$10500",
  },
  {
    Name: "Test2",
    Position: "Tester",
    Salary: "$5500",
  },
  {
    Name: "Test3",
    Position: "Developer",
    Salary: "$5500",
  },
  {
    Name: "Test4",
    Position: "Team Lead",
    Salary: "$7500",
  },
];

write("test.csv", fields, data);


Output:
"Name","Position","Salary"
"Test1","Manager","$10500"
"Test2","Tester","$5500"
"Test3","Developer","$5500"
"Test4","Team Lead","$7500"

答案 2 :(得分:1)

使用csv-write-stream函数将数据附加到csv文件中。

https://www.npmjs.com/package/csv-write-stream 添加带有标志“ a”的行

writer.pipe(fs.createWriteStream('out.csv',{flags:'a'}))

答案 3 :(得分:0)

使用json-2-csv

/**
 *  this function will create the file if not exists or append the 
 *   data if exists
 */

function exportToCsvFile(headersArray, dataJsonArray, filename) {

    converter.json2csvAsync(dataJsonArray, {prependHeader: false}).then(function (csv) {

    fs.exists(filename + '.csv', async function (exists) {

        if (!exists) {
            var newLine = "\r\n";
            var headers = ((headersArray ? headersArray : []) + newLine);

            exists= await createFileAsync(filename+ '.csv', headers);
        }

        if (exists) {
            fs.appendFile(filename + '.csv', csv, 'utf8', function (err) {
                if (err) {
                    console.log('error csv file either not saved or corrupted file saved.');
                } else {
                    console.log(filename + '.csv file appended successfully!');
                }
            });
        }
    });
}).catch(function (err) {
    console.log("error while converting from json to csv: " + err);
    return false;
});
}


function createFileAsync(filename, content) {
    return new Promise(function (resolve, reject) {
        fs.writeFile(filename, content, 'utf8', function (err) {
            if (err) {
                console.log('error '+filename +' file either not saved or corrupted file saved.');
                resolve(0);
            } else {
                console.log(filename + ' file created successfully!');
                resolve(1);
            }
        });
    });
}

答案 4 :(得分:0)

似乎,json2csv的最新版本具有称为.parse()的专用方法,可以将JSON转换为CSV兼容字符串。我尝试了json2csv.parse()转换器,它对我有用。

常见问题:

我在此处给出的解决方案中发现了一个常见问题。如果我们多次运行该方法,则解决方案不会在没有HEADER的情况下追加数据。

解决方案:

我使用了header提供的json2csv布尔选项来解决此问题。如果我们使用{header:false}选项进行解析,我们将获得数据作为行。

// Rows without headers.
rows = json2csv(data, { header: false });

下面是我上面提到的完全有效的代码:

示例代码:

下面是代码示例:

const fs = require('fs');
const path = require('path');
const json2csv = require('json2csv').parse;
const write = async (fileName, fields, data) => {
    // output file in the same folder
    const filename = path.join(__dirname, 'CSV', `${fileName}`);
    let rows;
    // If file doesn't exist, we will create new file and add rows with headers.    
    if (!fs.existsSync(filename)) {
        rows = json2csv(data, { header: true });
    } else {
        // Rows without headers.
        rows = json2csv(data, { header: false });
    }

    // Append file function can create new file too.
    fs.appendFileSync(filename, rows);
    // Always add new line if file already exists.
    fs.appendFileSync(filename, "\r\n");
}

调用Write函数

我们有3个参数:

fields = ['Name', 'Position', 'Salary'];
    data = [{
        'Name': 'Test1',
        'Position': 'Manager',
        'Salary': '$10500'
    },
    {
        'Name': 'Test2',
        'Position': 'Tester',
        'Salary': '$5500'
    }, {
        'Name': 'Test3',
        'Position': 'Developer',
        'Salary': '$5500'
    }, {
        'Name': 'Test4',
        'Position': 'Team Lead',
        'Salary': '$7500'
    }];

现在调用函数write

write('test.csv', fields, data);

每次我们调用上述方法时,它都会从新行开始写入。如果文件不存在,它将只写入一次标头。