Write to a CSV in Node.js

前端 未结 6 1146
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  情深已故
    2020-12-09 15:02

    In case you don't wanna use any library besides fs, you can do it manually.

    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')
    

提交回复
热议问题