Removing a Note
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 12 of 24.
done 2 should remove note 2, and people type anything after done.
Arguments are strings: Number('2') is 2 and Number('two') is NaN. Number.isInteger rejects NaN and 2.5 in one test; then check the range. Lists count from 1 and arrays from 0, so note n sits at index n - 1, and splice(i, 1) removes it.
// 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)}`);Challenge
Easydone <n>removes note n, saves, and printsDone: <text>.- A word that is not a note (
abc,0,2.5, a number past the end) printsNo note <word>to stderr and exits with1, changing nothing.
Run done 1, then list. Then try done abc.
Try it yourself
// Your notes tool starts here.
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);
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Node.js Basics
1Running JavaScript on Node
Hello, NodeCommand-Line ArgumentsCommands