1. 使用readline模塊逐行讀取流數據
1.1. 創建Interface對象
在readline模塊中,通過Interface對象的使用來實現逐行讀取流數據的處理。因此首先要創建Interface對象,在readline模塊中,可以通過createInterface方法來創建Interface對象.readline.createInterface(options),options為一個對象,屬性如下
// 輸入 exit, quit,q這三個任意之一的時候,會退出const readline = require('readline');let rl = readline.createInterface({ input: process.stdin, output: process.stdout, completer: completer});rl.on('line', (line) => { if (line === 'exit' || line === 'quit' || line === 'q') { rl.close(); } else { console.log('您輸入了:', line); }});rl.on('close', () => { console.log('行數據讀取操作被終止');});function completer(line) { const completions = '.help .error .exit .quit .q'.split(' '); let hits = completions.filter((c) => { return c.indexOf(line) === 0; }); return [hits.length ? hits : completions, line]}1.2. 使用Interface對象逐行讀取文件
原fs.js文件的內容
console.log('this is line 1');console.log('this is line 2');console.log('this is line 3');console.log('this is line 4');console.log('this is line 5');代碼內容
const readline = require('readline');const fs = require('fs');let file = fs.createReadStream('./fs.js');let out = fs.createWriteStream('./anotherFs.js');let index = 1;out.write('/*line' + index.toString() + ": */");let rl = readline.createInterface({ input: file, output: out, terminal: true});rl.on('line', (line) => { if (line === '') { rl.close(); } else { index++; out.write('/*line' + index.toString() + ': */'); }});生成的anotherFs.js文件的內容
/*line1: */console.log('this is line 1');/*line2: */console.log('this is line 2');/*line3: */console.log('this is line 3');/*line4: */console.log('this is line 4');/*line5: */console.log('this is line 5');/*line6: */2. 使用util模塊中提供的一些方法
新聞熱點
疑難解答
圖片精選