如何在nodejs json2csv中的现有csv文件中追加新行? [英] How to append new row in exist csv file in nodejs json2csv?

查看:396
本文介绍了如何在nodejs json2csv中的现有csv文件中追加新行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add new row in exist csv file? if csv file exist, then i don't want to add column header and just want to add new row after exist row in the file.

这是我正在尝试的代码:

Here is code which I'm trying:

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

推荐答案

以下代码将完成您要求的操作:

The following code will do what you asked:

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

  1. When run the first time- will write the headers
  2. Each run after that - will append json the data to the csv file

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) {
            if (err) throw err;
            console.log('file saved');
        });
    }
});

这篇关于如何在nodejs json2csv中的现有csv文件中追加新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆