組み込みモジュール
CoddyのNode.jsジャーニー「Node.jsの基礎」セクションの一部。レッスン 8/24。
メモはまもなくファイルに保存されますが、ファイルパスはコンピューターによって異なります。
Nodeには、このための独自のモジュールが用意されています。ファイルと同じように、node: 接頭辞を付けてインポートでき、インストールは不要です。path.join はパスの各部分を適切な区切り文字でつなぎ、path.basename は最後の部分を返します。os.homedir() はホームフォルダー、process.cwd() はプログラムの実行場所となるフォルダーです。
import os from 'node:os';
import path from 'node:path';
const file = path.join(os.homedir(), 'photos', 'cat.png');
console.log(file); // /home/ada/photos/cat.png
console.log(path.basename(file)); // cat.pngpath.join は各部分の間にスラッシュを1つ入れるので、photoscat.png のようになることはありません。
チャレンジ
簡単- 新しい
whereコマンドは、現在のフォルダーにあるnotes.jsonのフルパスを出力します:path.join(process.cwd(), 'notes.json')。 - 2行目には、そのパスのベース名が出力されます。
node notes.js whereを実行します。このファイルはまだ存在しません。第3章で作成します。
自分で試してみよう
// メモツールはここから始まります。
import { formatNote } from './format.js';
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(`Adding: ${formatNote(n, 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');
}
store.notes.forEach((note, i) => console.log(formatNote(i + 1, note)));
} else {
if (command) {
console.error(`Unknown command: ${command}`);
}
console.error('Usage: node notes.js <command> [words]');
process.exit(1);
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。