[github地址:https://github.com/ABCDdouyae...]node
採用流模式讀取.csv文件,每次讀取一行數據
對node流的二次封裝,更加易於使用
//將文件中的a所有替換爲z輸出到out.txt const through2 = require('through2'); const fs = require('fs'); fs.createReadStream('./test/enter.txt') .pipe(through2(function (chunk, enc, callback) { for (var i = 0; i < chunk.length; i++) if (chunk[i] == 97) chunk[i] = 122 // swap 'a' for 'z' this.push(chunk) callback() })) .pipe(fs.createWriteStream('./test/out.txt')) .on('finish', () => { console.log('完事') })
const through2 = require('through2'); const csv2 = require('csv2'); const fs = require('fs'); let all = []; fs.createReadStream('./test/enter.csv') .pipe(csv2()) .pipe(through2.obj(function (chunk, enc, callback) { this.push({ No : chunk[0], activity : chunk[1], time : chunk[2], money: chunk[3] }) callback() })) .on('data', (data)=>{ all.push(data) }) .on('end', ()=>{ fs.writeFile('./test/a.js', JSON.stringify(all), ()=>{ console.log('寫入完成') }) })
let Fc = through2.ctor(function(chunk, enc, callback){ console.log(chunk) for(var i=0;i<chunk.length;i++){ if(chunk[i]<=97){ chunk[i] = 98; } } console.log(chunk); this.push(chunk); callback(); }) fs.createReadStream('./test/enter.txt') .pipe(Fc()) .pipe(fs.createWriteStream('./test/out1.txt')) .on('finish', () => { console.log('完事') })