-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Node.js: Foundmental #89
Comments
BufferClass methodsBuffer.xxx()
Instance methods
Module methods
|
Streamconst stream = require('stream'); Types of Streams
Object ModelNode.js API 创建的所有stream本身操作都作用于String对象和Bufer对象(or Uint8Array). BufferingWritable 和 Readable streams 都把数据存储在内部buffer中, 可以分别使用 被Buffer的数据量是由
内部存贮中的数据达到上限 highWaterMark 后, stream便会停止读取源数据直到其中数据被消费.
API for Stream Consumersconst http = require('http');
const server = http.createServer((req, res) => {
// `req` is an http.IncomingMessage, which is a Readable Stream.
// `res` is an http.ServerResponse, which is a Writable Stream.
let body = '';
// Get the data as utf8 strings.
// If an encoding is not set, Buffer objects will be received.
req.setEncoding('utf8');
// Readable streams emit 'data' events once a listener is added.
req.on('data', (chunk) => {
body += chunk;
});
// The 'end' event indicates that the entire body has been received.
req.on('end', () => {
try {
const data = JSON.parse(body);
// Write back something interesting to the user:
res.write(typeof data);
res.end();
} catch (er) {
// uh oh! bad json!
res.statusCode = 400;
return res.end(`error: ${er.message}`);
}
});
});
server.listen(1337); Writable Streams
所有的 Writable streams 都实现了stream.Writable 这个类所定义的接口. Class: stream.WritableEvents:
Methods
Readable Streams
两种模式 三种状态
重要观念: Readable直到提供了消费函数或忽略函数才会产生数据. 如果消费函数作废或移除, Readable便会停止. 为了向后兼容的原因, 移除 如果Readable切换成flowing模式, 但并没有提供有效的消费函数, 那么数据就丢了: 例如, 没有提供data事件处理函数, 而直接调用了stream.resume() 所有的Readable stream 默认模式paused, 可以用以下三种方法来切换成flowing模式:
再次切换回paused模式可以使用一下两种方法:
三种状态 readable.readableFlowing = {null, false, true}
false期间数据会积累存储到内部buffer中, 期待resume(): data事件会停止, 但是数据生成不会. |
Refs
Current version Node.js v14.2.0
Official Docs
Buffer
Stream
File System
Path
URL
Query Strings
HTTP
TLS/SSL
HTTPs
HTTP/2
Net
Process
Child Process
Cluster
Worker Threads
Crypto
Errors
Events
Timers
Utilities
V8
VM
OS
The text was updated successfully, but these errors were encountered: