如何在nodejs中保存csv数据到.csv文件?



这是我的app.js"文件。

const { convertArrayToCSV } = require('convert-array-to-csv');
const converter = require('convert-array-to-csv');
const fs = require('fs')
const csv = require('csv-parser')
const randomWords = require('random-words')
const header = ['number', 'first', 'last', 'handle'];
const dataArrays = [
[1, 'Mark', 'Otto', '@mdo'],
[2, 'Jacob', 'Thornton', '@fat'],
[3, 'Larry', 'the Bird', '@twitter'],
];
const val = convertArrayToCSV(dataArrays, {
header,
separator: ','
});
console.log(val)

输出:

number,first,last,handle
1,Mark,Otto,@mdo  
2,Jacob,Thornton,@fat
3,Larry,the Bird,@twitter

我想保存这个"值"在我的设备上以。csv文件的形式。我该怎么做呢?请帮助。我被困在这里四个小时了。

文件系统库

你可以使用NodeJs的文件系统库

数据可以是:<string> | <Buffer> | <TypedArray> | <DataView> | <Object>

作为选项,您可以解析像

这样的编码
fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);

const { convertArrayToCSV } = require('convert-array-to-csv');
const converter = require('convert-array-to-csv');
const fs = require('fs')
const csv = require('csv-parser')
const randomWords = require('random-words')
const header = ['number', 'first', 'last', 'handle'];
const dataArrays = [
[1, 'Mark', 'Otto', '@mdo'],
[2, 'Jacob', 'Thornton', '@fat'],
[3, 'Larry', 'the Bird', '@twitter'],
];
const val = convertArrayToCSV(dataArrays, {
header,
separator: ','
});
console.log(val)

fs.writeFile('<pathtodirectory>/message.csv', val, (err) => {
      if (err) throw err;
      console.log('The file has been saved!');
    });    
const fs = require('fs')
const header = ['number', 'first', 'last', 'handle'];
const dataArrays = [
[1, 'Mark', 'Otto', '@mdo'],
[2, 'Jacob', 'Thornton', '@fat'],
[3, 'Larry', 'the Bird', '@twitter'],
];
const val = [header].concat(dataArrays).map(arr => arr.join(',')).join('rn');
fs.writeFile('filename.csv', val, err => {
  if(err) console.error(err);
  else console.log('Ok');
}););

相关内容

  • 没有找到相关文章

最新更新