Node js 2일차 - chalk-nodemon-yargs

00_8_3·2020년 11월 2일
0

간단 Node

목록 보기
3/27

Node js 2일차

2.1 chalk

chalk

>>> npm i chalk

const chalk require("chalk")

console.log(chalk.green("hello"))

2.2 nodemon

스크립트 자동 실행기?

nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.

nodemon

>>> npm i nodemon

const nodemon require("nodemon")

오류 발생 시

>>> Set-ExecutionPolicy Unrestricted
 
>>> nodemon -v

>>> nodemon app.js

2.3 process.args

>>> node app.js Test

console.log(process.argv)
/* argument vector */

>>> ["/users/ehgks/.nvm/versions/node/v11.0.0/bin/node",
"/users/ehgks/Desktop/node-course/notes-app/app.js",
"Test"]

/* array 형태로 출력됨, console.log(process.argv[2])처럼 접근 가능 */

2.3.1 응용

const command = process.argv[2]

if (command ==="add") {
	console.log("Adding note!")
    }

2.3.2 yargs (parsing)

yargs

1. 설치 및 기본
>>> npm i yargs@12.0.2

const yargs = require("yargs")

console.log(process.argv)
console.log(yargs.argv)

>>> node app.js add --title="Things to buy"

출력 >>> {_: ["add"], tittle: "Things to buy", ""$0": "app.js" }
2.버전확인
yargs.version("1.0.1")  // help

>>> node app.js --verison  //or  --help
출력 >>> 1.0.1
3. Customize yargs
// Create add command
yargs.command({
	command: "add",
	describe: "Add a new note",
	handler: function () {
		console.log("Adding a new Note!")
    }
    
})

// Create remove command
yargs.command({
	command: "remove",
    descibe: "Remove a note",
    handler: ()=>{
    	console.log("Removing the note")
    }
})

>>> node app.js add
출력 >>> Adding a new Note!
3.1 yargs builder && handler
yargs.command({
	command: "add",
	describe: "Add a new note",
	builder: {
		title: {
			describe: "Note title",
			demandOption: true,
            // argument로 title이 꼭 들어가야함 아니면 오류 출력
			type: "string" 
        },
        body:{
        	describe: "note body",
            demandOption: true,
            type: "string"
        }
    },
	handler: function (argv) {
    
        console.log("Title" + argv.title)
        console.log("Body" + argv.body)
    }
    
})

>>> node app.js add --title="my title"
출력 >>> Title: my title

0개의 댓글