Rimuovere una nota
Fa parte della sezione Fondamenti di Node.js del percorso Node.js di Coddy. Lezione 12 di 24.
done 2 dovrebbe rimuovere la nota 2, e le persone possono digitare qualsiasi cosa dopo done.
Gli argomenti sono stringhe: Number('2') è 2 e Number('two') è NaN. Number.isInteger rifiuta NaN e 2.5 in un unico controllo; poi controlla l'intervallo. Gli elenchi contano a partire da 1 e gli array da 0, quindi la nota n si trova all'indice n - 1, e splice(i, 1) la rimuove.
// 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)}`);Sfida
Faciledone <n>rimuove la nota n, salva e stampaDone: <text>.- Una parola che non corrisponde a una nota (
abc,0,2.5, un numero superiore al totale) stampaNo note <word>su stderr ed esce con1, senza modificare nulla.
Esegui done 1, poi list. Poi prova done abc.
Provalo tu
// Il tuo strumento per gli appunti inizia qui.
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);
}
Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.
Tutte le lezioni di Fondamenti di Node.js
1Eseguire JavaScript con Node
Ciao, NodeArgomenti della riga di comandoComandi