Menu
CoddyTech

读取输入

本课属于 Coddy Node.js 学习旅程的“Node.js 基础”单元。第 30 课,共 33 课。

如果列表已经存在于其他地方,一次只添加一条笔记会很慢。

程序也可以从 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。文本通常以换行符结尾,因此最后一行是空的:删除空行。

challenge icon

挑战

简单

如果你已经有一个列表,逐条输入笔记并使用 add 命令会很慢。添加一个 import 命令,从程序的输入流 stdin 一次读取多条笔记。

  1. 在 notes.js 中添加一个 import 命令。按照本课所示,使用 for await 将 stdin 的全部内容读入一个字符串。
  2. 将文本拆分为多行。去掉每行开头和结尾的空格,并跳过去掉空格后为空的行。
  3. 将剩下的每一行作为笔记添加,并使用 store.add 等待每次添加完成。你的 added 监听器仍会为每条笔记打印一行 Saved note。这是预期结果。
  4. 最后,打印 Imported 、添加的笔记数量以及 notes.。输入以下内容时:
    Buy bread
    Call the bank
    
    Water the plants
    node notes.js import 会将这三行保存为笔记。它会打印三行 Saved note,然后最后打印:
    Imported 3 notes.
    完全没有输入时,它只会打印:
    Imported 0 notes.

试试看:点击“运行”旁边的“输入”按钮。参数下方会打开一个输入框。在里面输入三行,中间一行留空。在 $ node notes.js 后面的输入框中输入 import,然后按 Enter。接着清空“输入”框,再次运行 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 在线编辑器