入力を読み取る
CoddyのNode.jsジャーニー「Node.jsの基礎」セクションの一部。レッスン 30/33。
リストがすでに別の場所にある場合、1つずつコマンドを入力してメモを追加するのは時間がかかります。
プログラムはstdinから入力を読み込むこともできます。キーボードで入力したテキストや、ファイルから送られたテキストです。ノートパソコンでは、cat numbers.txt | node sum.jsでファイルをstdinに送ります。|はパイプと呼ばれます。for await (const chunk of process.stdin)は、入力が終わるまで少しずつ読み込みます。読み込んだ部分を結合してから、行に分割します。
// cat numbers.txt | node sum.js
let input = '';
for await (const chunk of process.stdin) {
input += chunk;
}
const numbers = input.split('\n').filter((line) => line !== '').map(Number);
console.log(numbers.reduce((a, b) => a + b, 0));ここでは、ターミナルの入力ボックスがstdinに入力を渡します。テキストは通常、改行で終わるため、最後の行は空になります。空の行を取り除きましょう。
チャレンジ
簡単すでにどこかに一覧がある場合、メモを1つずつaddするのは時間がかかります。プログラムの入力(stdin)から一度に複数のメモを読み込むimportコマンドを追加しましょう。
notes.jsにimportコマンドを追加します。このレッスンで示したように、for awaitを使ってstdin全体を1つの文字列に読み込みます。- テキストを行に分割します。各行の先頭と末尾の空白を取り除き、取り除いた後に空になる行はスキップします。
- 残った各行をメモとして
store.addで追加し、それぞれの処理が終わるのを待ちます。addedリスナーは、引き続きメモごとにSaved noteの行を表示します。これは想定どおりです。 - 最後に、
Imported、追加したメモの数、そしてnotes.を表示します。次の入力の場合:Buy bread Call the bank Water the plantsnode notes.js importを実行すると、3行がメモとして保存されます。Saved noteの行が3行表示され、その後、最後に次のように表示されます:入力がまったくない場合、表示されるのは次の行だけです:Imported 3 notes.Imported 0 notes.
試してみましょう:「Run」の隣にある「Input」ボタンをクリックします。引数の下にボックスが開きます。そこに3行入力し、そのうち2行の間を空行にします。$ node notes.jsの後のボックスにimportと入力し、Enterキーを押します。次に、「Input」ボックスを空にして、もう一度importを実行します。Imported 0 notes.と表示されます。
自分で試してみよう
// あなたのメモツールはここから始まります。
import { rmSync } from 'node:fs';
import path from 'node:path';
import { formatNote } from './format.js';
import stats from './legacy/stats.cjs';
import store from './store.js';
const [command, ...words] = process.argv.slice(2);
const text = words.join(' ');
store.on('added', (note, n) => {
console.log(`Saved note ${n}.`);
});
const noteNumber = (word) => {
const n = Number(word);
if (!Number.isInteger(n) || n < 1 || n > store.notes.length) {
console.error(`No note ${word}`);
process.exit(1);
}
return n;
};
if (command === 'add') {
await store.add(text);
} else if (command === 'list') {
const owner = process.env.NOTES_OWNER ?? 'you';
console.log(`Notes for ${owner}`);
if (store.notes.length === 0) {
console.log('No notes yet');
}
const lines = store.notes.map((note, i) => formatNote(i + 1, note));
if (store.settings.sort === 'newest') {
lines.reverse();
}
lines.forEach((line) => console.log(line));
} else if (command === 'where') {
const file = path.join(process.cwd(), 'notes.json');
console.log(file);
console.log(path.basename(file));
} else if (command === 'stats') {
console.log(`${store.notes.length} notes, ${stats.countWords(store.notes)} words`);
} else if (command === 'done') {
const removed = await store.remove(noteNumber(words[0]));
console.log(`Done: ${removed}`);
} else if (command === 'remind') {
const note = store.notes[noteNumber(words[0]) - 1];
let count = 3;
const timer = setInterval(() => {
if (count > 0) {
console.log(count);
count -= 1;
} else {
console.log(note);
clearInterval(timer);
}
}, 200);
} else if (command === 'clear') {
rmSync('notes.json', { force: true });
console.log('Deleted notes.json');
} else {
if (command) {
console.error(`Unknown command: ${command}`);
}
console.error('Usage: node notes.js <command> [words]');
process.exit(1);
}
Node.jsの基礎のすべてのレッスン
自分で練習してみよう: Expressプレイグラウンド