Eine Notiz entfernen
Teil des Abschnitts Node.js-Grundlagen der Node.js-Journey von Coddy. Lektion 12 von 24.
done 2 sollte Notiz 2 entfernen, und nach done können beliebige Zeichen eingegeben werden.
Argumente sind Zeichenfolgen: Number('2') ist 2 und Number('two') ist NaN. Number.isInteger weist NaN und 2.5 mit einem Test zurück; prüfe dann den Wertebereich. Listen beginnen bei 1 zu zählen und Arrays bei 0, daher befindet sich Notiz n am Index n - 1, und splice(i, 1) entfernt sie.
// node seat.js 4
const seat = Number(process.argv[2]);
if (!Number.isInteger(seat) || seat < 1 || seat > 30) {
console.error(`No seat ${process.argv[2]}`);
process.exit(1);
}
console.log(`Row ${Math.ceil(seat / 6)}`);Aufgabe
Einfachdone <n>entfernt Notiz n, speichert und gibtDone: <text>aus.- Ein Wort, das keine Notiz ist (
abc,0,2.5, eine Zahl, die über das Ende hinausgeht), gibtNo note <word>auf stderr aus und wird mit1beendet, ohne etwas zu ändern.
Führe done 1 und dann list aus. Probiere anschließend done abc aus.
Probier es selbst
// Dein Notizentool 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(' ');
if (command === 'add') {
const n = store.add(text);
console.log(`Saved note ${n}.`);
} 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');
}
store.notes.forEach((note, i) => console.log(formatNote(i + 1, note)));
} 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 === '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);
}
Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.
Alle Lektionen in Node.js-Grundlagen
1JavaScript mit Node ausführen
Hallo, NodeKommandozeilenargumenteBefehle