Node.js Stream readable.setEncoding() 方法
Readable Stream 中的 readable.setEncoding () 方法用于设置读取数据的编码。
句法:
readable.setEncoding( encoding )
参数:此方法接受保存编码类型的单个参数编码。
返回值:它以编码形式返回数据。
下面的示例说明了 Node.js 中readable.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