可讀流中的visible.setEncoding()方法用於設置讀取數據的編碼。
用法:
readable.setEncoding( encoding )
參數:此方法接受保留編碼類型的單參數編碼。
返回值:它以編碼形式返回數據。
下麵的示例說明了Node.js中read.setEncoding()方法的使用:
範例1:
// Node.js program to demonstrate the
// readable.setEncoding() method
// Include fs module
const fs = require('fs');
// Create readable stream
const readable = fs.createReadStream("input.txt");
// Calling setEncoding method
readable.setEncoding('hex');
// Handling data event
readable.on('data', (chunk) => {
console.log(`${chunk}`);
});
// Displays that program
// is ended
console.log("Program ends!!");
輸出:
Program ends!! 48656c6c6f
範例2:
// Node.js program to demonstrate the
// readable.setEncoding() method
// Include fs module
const fs = require('fs');
// Create readable stream
const readable = fs.createReadStream("input.txt");
// Calling setEncoding method
readable.setEncoding('base64');
// Handling data event
readable.on('data', (chunk) => {
console.log(`${chunk}`);
});
// Displays that program
// is ended
console.log("Program ends!!");
輸出:
Program ends!! SGVs bG8=
參考: https://nodejs.org/api/stream.html#stream_readable_setencoding_encoding
相關用法
- node.js Stream writable.end()用法及代碼示例
- node.js Stream readable.read()用法及代碼示例
- node.js Stream readable.resume()用法及代碼示例
- node.js Stream writable.setDefaultEncoding()用法及代碼示例
- node.js Stream writable.cork()用法及代碼示例
- node.js Stream readable.isPaused()用法及代碼示例
- node.js Stream readable.pause()用法及代碼示例
- node.js Stream readable.pipe()用法及代碼示例
- node.js Stream writable.write()用法及代碼示例
- node.js Stream transform.destroy()用法及代碼示例
- node.js Stream readable.unpipe()用法及代碼示例
- node.js Stream writable.destroy()用法及代碼示例
- node.js Stream writable.uncork()用法及代碼示例
- node.js Stream readable.destroy()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Node.js | Stream readable.setEncoding() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。