환경 변수
Coddy Node.js 여정의 Node.js 기초 섹션에 포함된 레슨. 24개 중 5번째.
일부 설정은 프로그램 뒤에 입력하는 단어가 아니라 프로그램을 실행하는 사람이 정합니다.
환경 변수는 셸이 모든 프로그램에 전달하는 이름이 있는 문자열입니다. Node는 이를 process.env에 넣습니다. 설정되지 않은 변수는 undefined이므로 ??를 사용하면 기본값을 지정할 수 있습니다.
// CITY=Oslo node weather.js
const city = process.env.CITY ?? 'Lisbon';
console.log(`Weather for ${city}`);노트북에서 한 번만 실행할 때는 명령 앞에 변수 하나를 설정하면 됩니다. CITY=Oslo node weather.js를 실행하면 Weather for Oslo가 출력되고, node weather.js만 실행하면 Lisbon이 출력됩니다. 이름은 대소문자를 구분합니다. 코드 옆의 터미널에서는 변수를 설정하지 않으므로 항상 기본값이 표시됩니다.
챌린지
쉬움list는 먼저 제목을 출력합니다:Notes for <NOTES_OWNER>또는 변수가 설정되지 않은 경우Notes for you입니다.No notes yet는 다음 줄에 그대로 표시됩니다.
node notes.js list를 실행하세요. 검사 과정에서는 NOTES_OWNER=Ada node notes.js list도 실행합니다.
직접 해보기
// 메모 도구는 여기서 시작합니다.
const [command, ...words] = process.argv.slice(2);
const text = words.join(' ');
if (command === 'add') {
console.log(`Adding: ${text}`);
} else if (command === 'list') {
console.log('No notes yet');
} else {
if (command) {
console.error(`Unknown command: ${command}`);
}
console.error('Usage: node notes.js <command> [words]');
process.exit(1);
}