내장 모듈
Coddy Node.js 여정의 Node.js 기초 섹션에 포함된 레슨. 24개 중 8번째.
곧 메모를 파일에 저장하게 되며, 파일 경로는 컴퓨터마다 다릅니다.
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은 각 부분 사이에 슬래시 하나를 넣으므로 photoscat.png가 되는 일은 없습니다.
챌린지
쉬움- 새
where명령은 현재 폴더에서notes.json의 전체 경로를 출력합니다:path.join(process.cwd(), 'notes.json'). - 두 번째 줄은 해당 경로의 기본 이름을 출력합니다.
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);
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.