Menu
CoddyTech

Eingaben lesen

Teil des Abschnitts Node.js-Grundlagen der Node.js-Journey von Coddy. Lektion 30 von 33.

Notizen Befehl für Befehl hinzuzufügen, ist langsam, wenn die Liste bereits irgendwo anders vorhanden ist.

Ein Programm kann auch Eingaben von stdin lesen: Text, der über die Tastatur eingegeben oder aus einer Datei eingespeist wird. Auf einem Laptop sendet cat numbers.txt | node sum.js eine Datei an stdin; | wird Pipe genannt. for await (const chunk of process.stdin) liest sie Stück für Stück, bis sie endet. Füge die Stücke zusammen und teile sie dann in Zeilen auf.

// 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));

Hier füllt das Eingabefeld des Terminals stdin. Text endet normalerweise mit einem Zeilenumbruch, daher ist die letzte Zeile leer: Entferne leere Zeilen.

challenge icon

Aufgabe

Einfach

Notizen einzeln mit add einzugeben, dauert lange, wenn du bereits irgendwo eine Liste hast. Füge einen import-Befehl hinzu, der viele Notizen auf einmal aus der Eingabe des Programms, stdin, einliest.

  1. Füge in notes.js einen import-Befehl hinzu. Lies den gesamten Inhalt von stdin mit for await in eine Zeichenfolge ein, wie in der Lektion gezeigt.
  2. Teile den Text in Zeilen auf. Entferne die Leerzeichen am Anfang und Ende jeder Zeile und überspringe Zeilen, die danach leer sind.
  3. Füge jede verbleibende Zeile mit store.add als Notiz hinzu und warte jeweils darauf. Dein added-Listener gibt weiterhin für jede Notiz eine Saved note-Zeile aus. Das ist zu erwarten.
  4. Gib zuletzt Imported , die Anzahl der hinzugefügten Notizen und notes. aus. Bei dieser Eingabe:
    Buy bread
    Call the bank
    
    Water the plants
    speichert node notes.js import die drei Zeilen als Notizen. Es gibt drei Saved note-Zeilen und anschließend zuletzt Folgendes aus:
    Imported 3 notes.
    Ohne jegliche Eingabe gibt es nur Folgendes aus:
    Imported 0 notes.

Probiere es aus: Klicke neben „Run“ auf die Schaltfläche „Input“. Unter den Argumenten wird ein Feld geöffnet. Gib drei Zeilen ein, mit einer leeren Zeile zwischen zwei davon. Gib in das Feld nach $ node notes.js import ein und drücke die Eingabetaste. Leere dann das Feld „Input“ und führe import erneut aus: Du siehst Imported 0 notes..

Probier es selbst

// Dein Notiz-Tool beginnt hier.
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);
}

Alle Lektionen in Node.js-Grundlagen

Übe selbstständig: Express-Playground