Write to a CSV in Node.js

前端 未结 6 1149
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 14:47

I am struggling to find a way to write data to a CSV in Node.js.

There are several CSV plugins available however they only \'write\' to stdout.

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 15:19

    If you want to use a loop as you say you can do something like this with Node 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)
    })
    

提交回复
热议问题