Node.js/stream:修订间差异
来自康健生活
无编辑摘要 |
|||
| (未显示同一用户的29个中间版本) | |||
| 第7行: | 第7行: | ||
# 边读 边写,是边读边写的,读取一段文件,就将它写入 | # 边读 边写,是边读边写的,读取一段文件,就将它写入 | ||
# 流是基于事件的,所有的流对象都用 on绑定事件,并触发 | # 流是基于事件的,所有的流对象都用 on绑定事件,并触发 | ||
# 内存效率:不需要加载大量的数据到内存就可以处理 | |||
# 时间效率:一旦有了数据就开始处理,而不必等待传输完所有数据 | |||
代表数据流动方向:向内流(可读流),向外流(可写流)。常用的流形式是文件,和tcp套接字。流是以快为单位发送数据,通过监听‘data’事件,每一次得到一块数据即进行一次操作,当数据结束时,监听end事件,执行后续操作。可读流可以通过stream.pause();stream.resume()暂停恢复流。其中暂停流在写文件时会停止从该文件中读取数据,如果是TCP套接字则不会读取新的数据包,终止其他终端来的数据包。可写流是要从node向外输出的数据,可以是TCP连接也可以是文件。node不会在io操作上阻塞,写入的缓冲区如果被刷新,会发射drain事件,如果没有被刷新,数据将被存储在进程内存中。TCP连接是双向的,因此既是可读流也是可写流。以node作为服务器,则HTTP的请求是可读流,响应是可写流。通常在服务器端读取本地数据是快速的,即可读流是快速的。然而由于网络原因,很多响应即可写流是无法保证的,如果请求太多(在服务器的读写范围内),而响应太慢,会导致服务器的可写流填满。此时需要避免慢客户端(前端响应慢)的情况。 | |||
utf8中,中文占三个字符 | |||
<syntaxhighlight lang="javascript"> | |||
//判断是否处于流动模式 | |||
console.log(readStream._readableState.flowing); // null</syntaxhighlight> | |||
== 分类 == | |||
流分为四类:可写、可读、双工和转换。 | |||
=== 双工流 === | |||
=== 直通流 === | |||
PassThrough | |||
=== 获取流中的数据 === | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const content = await Promise.race(urls.map(host => this.fetch( | |||
`${host}/ajax/libs/${encodeURI(relativeFilePath)}` | |||
).then(res => res.body))).catch(err => err); | |||
const streamToString = (stream) => { | |||
const chunks = []; | |||
return new Promise((resolve, reject) => { | |||
stream.on('data', (chunk) => chunks.push(Buffer.from(chunk))); | |||
stream.on('error', (err) => reject(err)); | |||
stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); | |||
}); | |||
}; | |||
const content_str = await this.streamToString(content); | |||
</syntaxhighlight>|{{consoleout|<pre> | |||
// console.log(content) | |||
PassThrough {_readableState: ReadableState, _events: {…}, _eventsCount: 5,... | |||
// console.log(content_str) | |||
'/*!\n * Vue.js v2.6.14\n * (c) 2014-2021 Evan You\n * Released under the MIT License.\n */\n!function(e,t){"object"=... | |||
</pre>}}}} | |||
其他写法。 | |||
<syntaxhighlight lang="javascript"> | |||
async function streamToString(stream) { | |||
// lets have a ReadableStream as a stream variable | |||
const chunks = []; | |||
for await (const chunk of stream) { | |||
chunks.push(Buffer.from(chunk)); | |||
} | |||
return Buffer.concat(chunks).toString("utf-8"); | |||
}</syntaxhighlight> | |||
<div class="pageBoxGreen">需要注意 utf8 格式只适用于文本。</div> | |||
如果hai有读取图片等二进制文件。可直接转 base64。 | |||
<syntaxhighlight lang="javascript"> | |||
streamToBase64(stream) { | |||
const chunks = []; | |||
return new Promise((resolve, reject) => { | |||
stream.on('data', (chunk) => chunks.push(Buffer.from(chunk))); | |||
stream.on('error', (err) => reject(err)); | |||
stream.on('end', () => resolve(Buffer.concat(chunks).toString('base64'))); | |||
}); | |||
}</syntaxhighlight> | |||
=== other === | |||
==== 逐行流式传输 ==== | |||
== 实例对象的方法 == | |||
{| class="wikitable" | |||
|- | |||
! 标题文字 !! 标题文字 | |||
|- | |||
| data || 读数据时触发 | |||
|- | |||
| end || 数据读取完毕时触发 | |||
|- | |||
| error || 在接收和写入过程中发生错误时触发 | |||
|- | |||
| finish || 所有数据已被写入到底层系统时触发 | |||
|} | |||
== stream == | == stream == | ||
{| class="wikitable" | {| class="wikitable" | ||
|- | |- | ||
| 可写流 Readable Stream || [[/Writable|Writable]] || 可写入数据的流 | |||
| | |||
* [http://nodejs.cn/api/fs.html#fs_fs_createwritestream_path_options fs.createWriteStream()] | |||
* HTTP Reponse | |||
* process.stdout | |||
* TCP sockets | |||
* zlib streams | |||
* crypto streams | |||
|- | |- | ||
| [[/ | | 可读流|| [[/Readable|Readable]] || 可读取数据的流 | ||
| | |||
* [http://nodejs.cn/s/wiVPXD fs.createReadStream()] | |||
* HTTP Request | |||
* process.stdin | |||
* TCP sockets | |||
* zlib streams | |||
* crypto streams | |||
|- | |- | ||
| [[/ | | 双工流 || [[/Duplex|Duplex]] || 可读写的流 || [http://nodejs.cn/s/wsJ1o1 net.Socket] | ||
|- | |- | ||
| | | 转换流 || [[/Transform|Transform]] || 在读写过程中可以修改或转换数据的 Duplex 流 || [http://nodejs.cn/s/n6ED45 zlib.createDeflate()] | ||
| [[/Transform|Transform]] || 在读写过程中可以修改或转换数据的 Duplex 流 || [http://nodejs.cn/s/n6ED45 zlib.createDeflate()] | |||
|} | |} | ||
== 参数 == | == 参数 == | ||
{| class="wikitable" | {| class="wikitable" | ||
|- | |- | ||
| [[/highWaterMark |highWaterMark ]] || | | [[/highWaterMark |highWaterMark ]] || [[/objectMode|objectMode]] || 示例 | ||
|- | |- | ||
| 示例 || 示例 || 示例 | | 示例 || 示例 || 示例 | ||
| 第29行: | 第120行: | ||
| 示例 || 示例 || 示例 | | 示例 || 示例 || 示例 | ||
|} | |} | ||
== 读写 == | |||
简单的文件读写示例,读取文件将文件内容写入内存,再从内存中取出写入文件。缺陷是如果文件过大会内存溢出。 | |||
<syntaxhighlight lang="javascript"> | |||
const fs = require('fs'); | |||
const path = require('path'); | |||
const read2write = (source, target) => { | |||
fs.readFile(path.resolve(source), (err, data) => { | |||
if(err) return throw new Error(err.toString()); | |||
fs.writeFile(path.resolve(target), data, (err) => {}); | |||
}) | |||
};</syntaxhighlight> | |||
通过创建流进行边读边写。 | |||
<syntaxhighlight lang="javascript"> | |||
const fs = require('fs'); | |||
const path = require('path'); | |||
const read2write = (source, target) => { | |||
const rs = fs.createReadStream(source); | |||
const ws = fs.createWriteStream(target); | |||
rs.on('data', data => { | |||
ws.write(data); | |||
}); | |||
rs.on('end', () => { | |||
ws.end(); | |||
}); | |||
};</syntaxhighlight> | |||
补全代码,将读写进行限制。避免写入速度快于读取速度。 | |||
<syntaxhighlight lang="javascript"> | |||
const fs = require('fs'); | |||
const path = require('path'); | |||
const read2write = (source, target) => { | |||
const rs = fs.createReadStream(source); | |||
const ws = fs.createWriteStream(target); | |||
rs.on('data', data => { | |||
if (ws.write(data) === false) rs.pause(); | |||
}); | |||
ws.on('drain', () => { | |||
rs.resume(); | |||
}); | |||
rs.on('end', () => { | |||
ws.end(); | |||
}); | |||
};</syntaxhighlight> | |||
使用管道。 | |||
<syntaxhighlight lang="javascript"> | |||
fs.createReadStream('/path/to/source').pipe(fs.createWriteStream('/path/to/target'));</syntaxhighlight> | |||
=== 流的复用 === | |||
将一个流进行复用,留一旦被使用就会被消耗,但我们可以将流通过管道传输两次进行使用。 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const spawn = require('child_process').spawn; | |||
const PassThrough = require('stream').PassThrough; | |||
const bar = new PassThrough(); | |||
const biz = new PassThrough(); | |||
const foo = spawn('echo', ['kangkk']); | |||
foo | |||
.stdout.on('end', function() { | |||
console.log('foo end'); | |||
}) | |||
.pipe(bar) | |||
.on('end', function() { | |||
console.log('bar end'); | |||
}) | |||
.pipe(biz) | |||
.on('end', function() { | |||
console.log('biz end'); | |||
});</syntaxhighlight>|{{consoleout|<pre> | |||
foo end | |||
bar end | |||
</pre>}}}} | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const Readable = require('stream').Readable; | |||
const stream = require('stream'); | |||
const rs = new Readable(); | |||
rs.push('kangkk\n'); | |||
rs.push(null); | |||
const foo = rs.pipe(new stream.PassThrough()); | |||
const bar = rs.pipe(new stream.PassThrough()); | |||
foo.pipe(process.stdout); | |||
bar.pipe(process.stdout);</syntaxhighlight>|{{consoleout|<pre> | |||
kangkk | |||
kangkk | |||
</pre>}}}} | |||
背压。 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const Readable = require('stream').Readable; | |||
const stream = require('stream'); | |||
const rs = new Readable(); | |||
rs.push('kangkk\n'); | |||
rs.push(null); | |||
const foo = rs.pipe(new stream.PassThrough()); | |||
const bar = rs.pipe(new stream.PassThrough()); | |||
foo.on('data', function (data) { console.log('foo data:', data) }) | |||
foo.on('end', function () { | |||
bar.on('data', function (data) { console.log('bar data:', data) }) | |||
})</syntaxhighlight>|{{consoleout|<pre> | |||
foo data: <Buffer 6b 61 6e 67 6b 6b 0a> | |||
bar data: <Buffer 6b 61 6e 67 6b 6b 0a> | |||
</pre>}}}} | |||
== 转换 == | |||
=== stream2string === | |||
<syntaxhighlight lang="javascript"> | |||
function stream2String (stream) { | |||
const chunks = []; | |||
return new Promise((resolve, reject) => { | |||
stream.on('data', (chunk) => chunks.push(Buffer.from(chunk))); | |||
stream.on('error', (err) => reject(err)); | |||
stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); | |||
}) | |||
} | |||
const result = await streamToString(stream);</syntaxhighlight> | |||
=== stream2Buffer === | |||
<syntaxhighlight lang="javascript"> | |||
function stream2Buffer(stream) { | |||
return new Promise((resolve, reject) => { | |||
const buffers = []; | |||
stream.on('error', reject); | |||
stream.on('data', (data) => buffers.push(data)); | |||
stream.on('end', () => resolve(Buffer.concat(buffers))); | |||
}); | |||
} </syntaxhighlight> | |||
<syntaxhighlight lang="javascript"> | |||
const Duplex = require('stream').Duplex; | |||
function buffer2Stream(buffer) { | |||
const stream = new Duplex(); | |||
stream.push(buffer); | |||
stream.push(null); | |||
return stream; | |||
}</syntaxhighlight> | |||
== 技巧 == | == 技巧 == | ||
{| class="wikitable" | {| class="wikitable" | ||
| 第34行: | 第275行: | ||
| [[/发送文件|发送文件]] || [[/导流|导流]] || [[/Promise对象并发|Promise对象并发]] | | [[/发送文件|发送文件]] || [[/导流|导流]] || [[/Promise对象并发|Promise对象并发]] | ||
|- | |- | ||
| | | [[/柯里化并发|柯里化并发]] || [[/拷贝|拷贝]] || 示例 | ||
|- | |- | ||
| 示例 || 示例 || 示例 | | 示例 || 示例 || 示例 | ||
| 第48行: | 第289行: | ||
| 示例 || 示例 || 示例 | | 示例 || 示例 || 示例 | ||
|} | |} | ||
== 其他 == | |||
{| class="wikitable" | |||
|- | |||
| [[/网络流|网络流]] || 示例 || 示例 | |||
|- | |||
| 示例 || 示例 || 示例 | |||
|- | |||
| 示例 || 示例 || 示例 | |||
|} | |||
== 实现 == | |||
== 参考 == | |||
* http://nodejs.cn/api/stream.html#event-pipe | |||