Home > Web Front-end > JS Tutorial > Node.js Stream(stream)

Node.js Stream(stream)

黄舟
Release: 2017-01-17 15:49:49
Original
1104 people have browsed it

Learning points:

Read data from the stream

Write to the stream

Pipe stream

Chain stream

Node.js Stream(Stream)

Read data from the stream

Case: main.js

[code]var fs = require('fs');
var data = '';
// 创建可读流
var readerStream = fs.createReadStream('input.txt');
// 设置utf8编码
readerStream.setEncoding('UTF8');
// 处理流事件
// data 当有数据可读时触发
readerStream.on('data', function (chunk) {
    data += chunk;
});
// end 当没有数据读时触发
readerStream.on('end', function () {
    console.log(data);
});
// error  在接收和写入过程中发生错误时触发。
readerStream.on('error', function (err) {
    console.log(err.stack);
});
console.log('程序执行完毕。');
Copy after login

Node.js Stream(stream)

##Write to the stream


Case: main2.js

[code]var fs = require('fs');
var data = '我是谁?';
// 创建写入流
var writeStream = fs.createWriteStream('ouput.txt');
// 编码
writeStream.write(data, 'UTF8');
// 标记文件末尾
writeStream.end();
// 处理流事件
// finish 所有数据已被写入到底层系统时触发。
writeStream.on('finish', function () {
    console.log('写入完成');
});
// error 在读入和写入数据是触发
writeStream.on('error', function (err) {
    console.log(err.stack);
});
console.log('程序执行完毕。');
Copy after login

Node.js Stream(stream)

Pipeline flow


Input data from one stream into another stream

Case: pipe.js

[code]var fs = require('fs');
// 创建可读流
var readerStream = fs.createReadStream('input.txt');
// 创建写入流
var writeStream = fs.createWriteStream('ouput.txt');
// 管道读写
readerStream.pipe(writeStream);
console.log('程序执行完毕。');
Copy after login

Node.js Stream(stream)

Chain flow


is to connect multiple input and output streams

Case: compression File express.js

[code]var fs = require('fs');
var zlib = require('zlib');
// 将 input.txt 压缩为 input.gz
fs.createReadStream('input.txt')
    .pipe(zlib.createGzip())
    .pipe(fs.createWriteStream('input.gz'));
console.log('文件压缩完毕');
Copy after login

Node.js Stream(stream)

Case: Decompress the file decompress.js

[code]var fs = require('fs');
var zlib = require('zlib');
// 解压 input.gz 为 input.gz.txt
fs.createReadStream('input.gz')
    .pipe(zlib.createGunzip())
    .pipe(fs.createWriteStream('input.gz.txt'));
console.log('解压文件完毕');
Copy after login

Node.js Stream(stream)

The above is Node.js Stream( Stream) content, for more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template