해당 글은 Node.js 교과서의 내용을 요약, 정리한 글입니다.
Command Line Interface
콘솔 창을 통해 프로그램을 수행하는 환경을 뜻한다.
반대되는 말로는 GUI(Graphic User Interface)가 있다.
//package.json
{
"name": "node-cli",
"version": "0.0.1",
"description": "book",
"main": "index.js",
"author": "jimmy0006",
"license": "ISC",
"bin":{
"cli":"./index.js"
}
}
//index.js
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output:process.stdout,
});
rl.question('안녕하세요(y/n)?',(answer)=>{
if(answer === 'y'){
console.log('감사합니다');
}else if(answer==='n'){
console.log('ㅠㅠ');
}else{
console.log('y 또는 n을 입력해주세요');
}
rl.close();
});
$npx cli
로 실행시킬 수 있다.
더 나아가면 명령어로 html 또는 익스프레스 라우터 파일 템플릿을 만들어 줄 수 있다.
CLI 프로그램을 위한 라이브러리가 많지만 이 책에서는 commander를 사용한다.
$npm i commander@5 inquirer chalk
//command.js
const {program} = require('commander');
program
.version('0.0.1','-v, --version')
.name('cli');
program
.command('template <type>')
.usage('<type> --filename [filename] --path [path]')
.description('템플릿을 생성합니다.')
.alias('tmpl')
.option('-f, --filename [filename]','파일명을 입력하세요','index')
.option('-d, --directory [path]','생성 경로를 입력하세요','.')
.action((type, options)=>{
console.log(type,options.filename, options.directory);
});
program
.command('*',{noHelp:true})
.action(()=>{
console.log('해당 명령어를 찾을 수 없습니다.')
program.help();
});
program
.parse(process.argv);
version: 프로그램의 버전
usage: 명령어의 사용법을 설정할 수 있다. []는 선택이라는 의미이다.
name: 명령어의 이름
command: 명령어를 설정하는 메서드, <> 는 필수의 의미이다.
description: 명령어에 대한 설명을 설정하는 메서드
alias: 명령어의 별칭을 설정
option: 명령어에 대한 부가적인 옵션 설정
requiredOption: option과 같은 역할을 하지만 필수로 입력해야 하는 옵션을 지정할때 사용한다.
action: 명령어에 대한 실제 동작을 정의하는 메서드
help: 설명서를 보여주는 메서드
parse: program객체의 마지막에 붙이는 메서드, process.argv를 인수로 받아서 명령어와 옵션을 파싱한다.