Node.jsストリームモジュール
例
書き込み可能なストリームへの書き込み:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello
World!');
res.end();
}).listen(8080);
定義と使用法
Streamモジュールは、ストリーミングデータを処理する方法を提供します。
ストリームには、読み取り可能と書き込み可能の2つのタイプがあります。
読み取り可能なストリームの例は、http.createServer()メソッドを使用するときに取得する応答オブジェクトです。
書き込み可能なストリームの例は、http.createServer()メソッドを使用するときに取得するリクエストオブジェクトです。
構文
一部のメソッドは、http.createServer()などの読み取り/書き込み可能なストリームオブジェクトを返します。その場合は、ストリームモジュールを含める必要はありません。
それ以外の場合、アプリケーションにStreamモジュールを含めるための構文は次のとおりです。
var stream = require('stream');
読み取り可能なストリームのプロパティとメソッド
Method | Description |
---|---|
isPaused() | Returns true if the state of the readable stream is paused, otherwise false |
pause() | Pauses the readable stream |
pipe() | Turns the readable stream into the specified writable stream |
read() | Returns a specified part of the readable stream |
resume() | Resumes a paused stream |
setEncoding() | Sets the character encoding of the readable stream |
unpipe() | Stops turning a readable stream into a writable stream, caused by the pipe() method |
unshift() | Pushes some specified data back into the internal buffer |
wrap() | Helps reading streams made by older Node.js versions |
書き込み可能なストリームのプロパティとメソッド
Method | Description |
---|---|
cork() | Stops the writable stream and all written data will be buffered in memory |
end() | Ends the writable stream |
setDefaultEncoding() | Sets the encoding for the writable stream |
uncork() | Flushes all data that has been buffered since the cork() method was called |
write() | Writes data to the stream |