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のReadStreamの振る舞いを確認してみる

Posted at

前準備

環境

OS:Windows 11 Home 64 ビット オペレーティング システム
CPU:11th Gen Intel(R) Core(TM) i7-1185G7 @ 3.00GHz 3.00 GHz
RAM:32.0 GB
Node.js:Node.js v20.4.0.

入力用テキストファイルを作成する

in.txt
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
(中略)
1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890

ログ出力用関数を準備する

fDateTime.js
module.exports = function() {
    //formatted DateTime
    date = new Date();
    const yyyy = date.getFullYear();
    const mm = ('0' + (date.getMonth() + 1)).slice(-2);
    const dd = ('0' + date.getDate()).slice(-2);
    const hh = ('0' + date.getHours()).slice(-2);
    const mi = ('0' + date.getMinutes()).slice(-2);
    const ss = ('0' + date.getSeconds()).slice(-2);
    const ms = ('0' + date.getMilliseconds()).slice(-3);
    return yyyy + mm + dd + hh + mi + ss + '.' + ms;
}

機能を実装する

fs_readStream.js
const fDateTime = require('.\\fDateTime.js');

const IN_FILE = "data\\in.txt";
const OUT_FILE = "data\\out.txt";

console.log("ファイル取得(非同期・stream):"+IN_FILE);

const fs = require("fs");
const rStream = fs.createReadStream(IN_FILE);
const wStream = fs.createWriteStream(OUT_FILE);

rStream.on('data', chunk => {
    console.log(`chunk Length:${chunk.length} (bytes)`);
    return wStream.write(chunk);
});

rStream.on('end', () => {
    return wStream.end();
});

動作させてみる

image.png

振る舞い確認用のログを付加する

fs_readStream_addDateTimeLog.js
const fDateTime = require('.\\fDateTime.js');

const IN_FILE = "data\\in.txt";
const OUT_FILE = "data\\out.txt";

console.log("ファイル取得(非同期・stream):"+IN_FILE);
console.log(`main start:${fDateTime()}`);

const fs = require("fs");
const rStream = fs.createReadStream(IN_FILE);
const wStream = fs.createWriteStream(OUT_FILE);

rStream.on('data', chunk => {
    console.log(`chunk Length:${chunk.length} (bytes):${fDateTime()}`);
    return wStream.write(chunk);
});

rStream.on('end', () => {
    console.log(`readStream.on end  :${fDateTime()}`);
    return wStream.end();
});

console.log(`main end  :${fDateTime()}`);

動作させて非同期の振る舞いを確認する

image.png

以下のサイトを参考にしました

nodejs.org File system

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?