前準備
環境
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();
});
動作させてみる
振る舞い確認用のログを付加する
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()}`);