node.js - how to write an array to file

前端 未结 5 1527
礼貌的吻别
礼貌的吻别 2020-12-13 03:46

I have a sample array as follows

var arr = [ [ 1373628934214, 3 ],
  [ 1373628934218, 3 ],
  [ 1373628934220, 1 ],
  [ 1373628934230, 1 ],
  [ 1373628934234,         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 04:33

    To do what you want, using the fs.createWriteStream(path[, options]) function in a ES6 way:

    const fs = require('fs');
    const writeStream = fs.createWriteStream('file.txt');
    const pathName = writeStream.path;
     
    let array = ['1','2','3','4','5','6','7'];
      
    // write each value of the array on the file breaking line
    array.forEach(value => writeStream.write(`${value}\n`));
    
    // the finish event is emitted when all data has been flushed from the stream
    writeStream.on('finish', () => {
       console.log(`wrote all the array data to file ${pathName}`);
    });
    
    // handle the errors on the write process
    writeStream.on('error', (err) => {
        console.error(`There is an error writing the file ${pathName} => ${err}`)
    });
    
    // close the stream
    writeStream.end();
    

提交回复
热议问题