写入Node.js中的CSV

lymgl2op  于 2023-01-01  发布在  Node.js
关注(0)|答案(8)|浏览(337)

我一直在努力寻找一种方法来将数据写入Node.js中的CSV
有几个CSV插件可用,但他们只'写'到标准输出。
理想情况下,我希望使用循环在逐行的基础上进行写入。

qyyhg6bp

qyyhg6bp1#

您可以使用文件系统(https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback):

var dataToWrite;
var fs = require('fs');

fs.writeFile('form-tracking/formList.csv', dataToWrite, 'utf8', function (err) {
  if (err) {
    console.log('Some error occured - file either not saved or corrupted file saved.');
  } else{
    console.log('It\'s saved!');
  }
});
nwo49xxi

nwo49xxi2#

node-csv-parsernpm install csv)的文档特别声明它可以用于流(参见fromStreamtoStream),因此没有硬编码使用stdout。
当您使用npm search csv时,还会出现其他几个CSV解析器--您可能也想看看它们。

gtlvzcf8

gtlvzcf83#

下面是一个简单的示例,使用csv-stringify将适合内存的数据集写入使用fs.writeFile的csv文件。

import stringify from 'csv-stringify';
import fs from 'fs';

let data = [];
let columns = {
  id: 'id',
  name: 'Name'
};

for (var i = 0; i < 10; i++) {
  data.push([i, 'Name ' + i]);
}

stringify(data, { header: true, columns: columns }, (err, output) => {
  if (err) throw err;
  fs.writeFile('my.csv', output, (err) => {
    if (err) throw err;
    console.log('my.csv saved.');
  });
});
myzjeezk

myzjeezk4#

如果你想使用一个循环,你可以这样做节点fs:

let fs = require("fs")

let writeStream = fs.createWriteStream('/path/filename.csv')

someArrayOfObjects.forEach((someObject, index) => {     
    let newLine = []
    newLine.push(someObject.stringPropertyOne)
    newLine.push(someObject.stringPropertyTwo)
    ....

    writeStream.write(newLine.join(',')+ '\n', () => {
        // a line was written to stream
    })
})

writeStream.end()

writeStream.on('finish', () => {
    console.log('finish write stream, moving along')
}).on('error', (err) => {
    console.log(err)
})
vulvrdjw

vulvrdjw5#

如果您不想使用除fs之外的任何库,您可以手动执行此操作。

let fileString = ""
let separator = ","
let fileType = "csv"
let file = `fileExample.${fileType}`

Object.keys(jsonObject[0]).forEach(value=>fileString += `${value}${separator}`)
    fileString = fileString.slice(0, -1)
    fileString += "\n"

    jsonObject.forEach(transaction=>{
        Object.values(transaction).forEach(value=>fileString += `${value}${separator}`)
        fileString = fileString.slice(0, -1)
        fileString += "\n"
    })

fs.writeFileSync(file, fileString, 'utf8')
ddhy6vgd

ddhy6vgd6#

对于喜欢fast-csv的用户:

const { writeToPath } = require('@fast-csv/format');

const path = `${__dirname}/people.csv`;
const data = [{ name: 'Stevie', id: 10 }, { name: 'Ray', id: 20 }];
const options = { headers: true, quoteColumns: true };

writeToPath(path, data, options)
        .on('error', err => console.error(err))
        .on('finish', () => console.log('Done writing.'));
6jjcrrmo

6jjcrrmo7#

如果您不想使用除文件系统之外的任何库,您可以手动执行此操作。此外,您还可以在要写入CSV文件时筛选数据

router.get('/apiname', (req, res) => {
 const data = arrayOfObject; // you will get from somewhere
 /*
    // Modify old data (New Key Names)
    let modifiedData = data.map(({ oldKey1: newKey1, oldKey2: newKey2, ...rest }) => ({ newKey1, newKey2, ...rest }));
 */
 const path = './test'
 writeToFile(path, data, (result) => {
     // get the result from callback and process
     console.log(result) // success or error
   });
});

writeToFile = (path, data, callback) => {
    fs.writeFile(path, JSON.stringify(data, null, 2), (err) => { // JSON.stringify(data, null, 2) help you to write the data line by line
            if (!err) {
                callback('success');
                // successfull
            }
            else {
                 callback('error');
               // some error (catch this error)
            }
        });
}
wvt8vs2t

wvt8vs2t8#

这是在nest js中为我工作的代码

import { Parser } from "json2csv";

 const csv = require('csvtojson');

      const csvFilePath = process.cwd() + '/' + file.path;

      let csv data  = await csv().fromFile(csvFilePath); /// read data from csv into an array of json 
          

/// * from here how to write data into csv *

          data.push({
                label: value,
                .......
          })                 
        }

        const fields = [
         'field1','field2', ... 
        ]
        
        const parser = new Parser({ fields, header:false }); /// if dont want header else remove header: false
        const csv = parser.parse(data);
        appendFileSync('./filename.csv',`${csv}\n`); // remove /n if you dont want new line at the end

相关问题