簡體   English   中英

如何在nodejs json2csv中的現有csv文件中附加新行?

[英]How to append new row in exist csv file in nodejs json2csv?

我想在現有的 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);
  }
});

以下代碼將執行您的要求:

  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,
  header: 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');
    });
  }
});

似乎,最新版本的json2csv有一個名為.parse()專用方法來將 JSON 轉換為 CSV 兼容的字符串。 我試過json2csv.parse()轉換器,它對我json2csv.parse()

常見問題:

我在此處給出的解決方案中發現了一個常見問題。 如果我們多次運行該方法,則解決方案不會在沒有HEADER情況下追加數據。

解決方法:

我使用了json2csv提供的header boolean 選項來解決這個問題。 如果我們使用{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);

每次我們調用上述方法時,它都會從新行開始寫入。 如果文件不存在,它只寫入一次頭文件。

我對函數的行為方式進行了一些更改,現在我使用 2 種方法驗證是否有標題,如果存在,我將忽略它並添加行,如果沒有,我添加標題,從對象中刪除引號並傳遞一些等待,因為它的功能是同步的,沒有等待,所以異步沒有意義哈哈哈

傳遞給 filename 的 CSV 值是節點將在項目根目錄中查找以保存最終文檔的文件夾的名稱

🇧🇷

Fiz umas mudanças em como a função se comporta, agora eu valido com 2 métodos seexiste cabeçalho, seexistir eu ignoro ele e adiciono as row, se não eu adiciono o cabeçalho, removi as aspas dos, passão unobjet fun時代同步 e não tinha nenhum await então não fazia sentido ser async haha​​ha

O valor CSV passado para o nome do arquivo é o nome da pasta que o nó procurará na raiz do projeto para salvar seu documento final

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"

使用 csv-write-stream 函數將數據附加到 csv 文件中。

https://www.npmjs.com/package/csv-write-stream添加這一行,帶有標志“a”

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM