0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Node.js Stream 個人的まとめ

Posted at

ストリーム(Stream)とは

  • ストリームとはファイルのデータ(Buffer等)を読み込んだり、読み込んだデータを別のファイルに書き込むことができるインターフェースのこと
    「インターフェース」とは複数のものをつなぐ技術や方法

A stream is an abstract interface for working with streaming data in Node.js. The node:stream module provides an API for implementing the stream interface.
There are many stream objects provided by Node.js. For instance, a request to an HTTP server and process.stdout are both stream instances.
Streams can be readable, writable, or both. All streams are instances of EventEmitter.

Readable Stream

  • データ入力元のこと
  • fs.createReadStreamで返されるストリーム

Writable Stream

  • データ出力先のこと
  • fs.createReadStreamで返されるストリーム
stream
// 必要なモジュールを読み込む
import * as fs from 'fs';

// 読み込み用のStreamを作成(拡張子がcsvでも可能)
const rs = fs.createReadStream('hoge.pdf');

// 書き込み用のStreamを作成
const ws = fs.createWriteStream('huga.odf');

// 読み込んだpdfのBefferをWritableStreamに書き込む
rs.pipe(ws)

例 : gzipの圧縮

gzip
import * as fs from 'fs';
import * as zlib from 'zlib';

// gzipの圧縮1
const gzip = zlib.createGzip();
const rs = fs.createReadStream('hoge.txt');
const ws = fs.createWriteStream('huga.txt.gz');
rs.pipe(gzip).pipe(ws);

// gzipの圧縮2(レスポンスにpipe)
fs.createReadStream('hoge.txt')
  .pipe(zlib.createGzip())
  .pipe(fs.createWriteStream('huga.txt.gz'))
  .pipe(res)

参考記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?