首頁 > web前端 > js教程 > 主體

在Node.js中如何使用readline模組與util模組

亚连
發布: 2018-06-02 11:49:39
原創
1370 人瀏覽過

本篇文章主要介紹了Node.js readline模組與util模組的使用,現在分享給大家,也給大家做個參考。

1. 使用readline模組逐行讀取流資料

1.1. 建立Interface物件

在readline模組中,透過Interface物件的使用來實現逐行讀取流資料的處理。因此首先要建立Interface對象,在readline模組中,可以透過createInterface方法來建立Interface對象.readline.createInterface(options),options為一個對象,屬性如下

  1. #input: 屬性值為一個可用於讀取流資料的對象,用於指定讀入資料的來源。

  2. output: 屬性值為一個可用來寫入流資料的對象,用於指定資料的輸出目標。

  3. computer: 屬性值為函數,用來指定Tab補全處理。函數的參數值會自動設定為從該行中讀入的Tab字元之前的數據,該函數應該傳回一個由所有用於Tab補全時的匹配字串組成的數組以及從該行中讀入的Tab字元之前的資料。

  4. terminal: 此屬性為布林類型的屬性,當需要像終端機一樣即時將輸入資料流進行輸出,且需要在輸出資料中寫入ANSI/VT100控制字串時,需要將該屬性值設為true,預設屬性值等於output屬性值物件的isTTY屬性值。

// 输入 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模組中提供的一些方法

format方法

類似於C語言中的printf方法,將第一個參數值作為一個格式化字串,將其他參數值作為該格式化字串中所使用的各中參數,傳回一個經過格式化處理後的字串.util.format('您輸入了%d個參數,參數值分別為%s,%s,%s',3,'nice','excelent','holy');
格式化字串中,可以使用的參數指定符號

  1. *`%s`:用於指定字串參數

  2. #*`%d`:用於指定數值參數,包括整數及浮點數

  3. *`%j`:用來指定一個`JSON`物件

  4. *`%%`:用來指定一個百分號

  5. *如果格式化字串中使用的參數個數多於format方法中使用的除了`format`參數之外的其他參數,則格式化字串中多於的參數將不被替換.`console.log(util.format('%s:%s','one'));`

  6. *如果格式化字串中使用的參數個數少於`format`方法中使用的除了`format`參數之外的其他參數,則根據`format`方法中多於參數值的類型自動將其轉換為字串,中間使用一個空格進行分割.

inspect(object,[options])傳回一個字串,該字串包含了物件的資訊,在偵錯應用程式的過程中非常有用.

  1. *`showHidden`如果為`true`,則`object`的不可枚舉的符號與屬性也會被包含在格式化後的結果中.默認為`false.`

  2. *`depth`指定格式化`object`時遞歸的次數.這對查看大型複雜物件很有用.預設為`2`.若要無限遞歸則傳入`null`.

  3. *`colors`如果為`true`,則輸出樣式使用`ANSI`顏色代碼.預設為` false`.顏色可自訂.

  4. *`customInspect`如果為`false`,則`object`上自訂的`inspect(depth,opts)`函數不會被呼叫.預設為`true`.

  5. *`showProxy`如果為`true`,則`Proxy`物件的物件和函數會展示它們的` target`和`handler`物件.預設為`false`.

  6. *`maxArrayLength`指定格式化時陣列和`TypedArray`元素能包含的最大數量.預設為`100`.設為`null`則明確全部數組元素.設為`0*`或負數則不顯式數組元素.

  7. *`breakLength `一個物件的鍵被拆分成多行的長度.設為`Infinity`則格式化一個物件為單行.預設為`60`.

自訂util.inspect顏色

可以透過util.inspect.styles和util.inspect.colors屬性全域自訂util.inspect的顏色輸出(如果已啟用)

const util = require('util');
console.log(util.format('您输入了%d个参数,参数值分别为%s,%s,%s', 3, 'nice', 'excelent', 'holy'));
//您输入了3个参数,参数值分别为nice,excelent,holy
console.log(util.format('一个JSON对象%j', {'name': 'jack', 'age': 25}));
// 一个JSON对象{"name":"jack","age":25}
console.log(util.format('一个百分号%'));// 一个百分号%
console.log(util.format('%s:%s', 'one'));// one:%s
console.log(util.format('%s', 'one', 'two', 'three', {'name': 'jack'}));

function test(one, two) {
  return one + two;
}

let parent = new Object();
parent.name = 'parent';
parent.func = test;

let child1 = new Object();
child1.name = 'child1';
parent.child1 = child1;

let child2 = new Object();
child2.name = 'child2';
child1.child = child2;

let child3 = new Object();
child3.name = 'child3';
child2.child = child3;

child2.inspect = function (depth) {
  return util.inspect(this, {depth: depth - 2, customInspect: false})
};
console.log(util.inspect(parent, {customInspect: true, depth: 4}));
/**
 * { name: 'parent',
 *  func: [Function: test],
 *  child1:
 *  { name: 'child1',
 *   child: { name: 'child2', child: [Object], inspect: [Function] } } }
 * **/
登入後複製

上面是我整理給大家的,希望今後對大家有幫助。

相關文章:

vue輪播圖外掛程式vue-concise-slider的使用

vue頁面離開後執行函數的實例

解決vue頁面重新整理或後退參數遺失的問題

以上是在Node.js中如何使用readline模組與util模組的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!