본문 바로가기
Programming/Node.js

Node.js에서 yargs npm 모듈 사용하는 방법

by 혀코 2019. 12. 27.

안녕하세요. 혀코입니다.

오늘은 Node.js에서 yargs npm 모듈을 사용하는 방법에 대해서 알아보겠습니다.

$ touch app.js
$ npm init
$ npm install yargs

app.js를 만들고 npm 초기화를 하고, yargs npm 라이브러리를 설치했습니다.

 

yargs npm 라이브러리를 사용하기 위해서 app.js 상단에 포함시켜 줍니다.

const yargs = require('yargs')

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

이렇게 app.js 를 업데이트 해주고, node 명령어를 실행해 줍니다.

$ node app.js

그러면 다음과 같은 결과가 나타납니다.

[
  'D:\\Programs\\nodejs\\node.exe',
  'D:\\hugo\\playground\\nodejs\\basics\\app.js'
]
{ _: [], '$0': 'app.js' }

 

 

이번에는 app.js는 그대로 둔 상태로 node 명령어를 다음과 같이 실행해 줍니다.

$ node app.js add --title="I am Iron man"

그러면 다음과 같은 결과가 나타납니다.

[
  'D:\\Programs\\nodejs\\node.exe',
  'D:\\hugo\\playground\\nodejs\\basics\\app.js',
  'add',
  '--title=I am Iron man'
]
{ _: [ 'add' ], title: 'I am Iron man', '$0': 'app.js' }

 

 

여기서, node 명령어를 다음과 같이 실행해 줍니다.

$ node app.js --help

 

[
  'D:\\Programs\\nodejs\\node.exe',
  'D:\\hugo\\playground\\nodejs\\basics\\app.js',
  '--help'
]
옵션:
  --help     도움말을 보여줍니다                                          [여부]
  --version  버전 넘버를 보여줍니다    

 

그래서 버전 확인을 해보겠습니다.

$ node app.js --version

1.0.0 이 표시됩니다.

 

그럼 yargs 를 이용해서 버전을 변경해 보도록 하겠습니다.

const yargs = require('yargs')

yargs.version('1.1.0')

console.log(yargs.argv)

다시 버전 확인을 해보겠습니다.

$ node app.js --version

1.1.0 이 표시되는 것을 확인할 수 있습니다.

 

 

yargs를 사용해서 4가지 명령어 add, remove, read, list 중 add를 세팅해 보겠습니다.

const yargs = require('yargs')

yargs.version('1.1.0')

yargs.command({
    command: 'add',
    describe: 'Add a new thing',
    handler: function() {
        console.log('Adding a new thing!')
    }
})

console.log(yargs.argv)

이렇게 한 다음, node --help 기능을 실행해 봤습니다.

$ node app.js --help

 

app.js [명령]

명령:
  app.js add  Add a new thing

옵션:
  --help     도움말을 보여줍니다                                          [여부]
  --version  버전 넘버를 보여줍니다 

이번에는 옵션 뿐만 아니라, 명령어 섹션이 새롭게 추가된 것을 확인할 수 있습니다.

 

이번에는 add 명령어를 사용해 보겠습니다.

$ node app.js add
Adding a new note!
{ _: [ 'add' ], '$0': 'app.js' }

그럼 위와 같은 결과가 표시됩니다. 

 

이번에는 yargs를 사용해서 4가지 명령어 add, remove, read, list 중 remove를 세팅해 보겠습니다.

const yargs = require('yargs')

yargs.version('1.1.0')

yargs.command({
    command: 'add',
    describe: 'Add a new thing',
    handler: function() {
        console.log('Adding a new thing!')
    }
})

yargs.command({
    command: 'remove',
    describe: 'Remove a thing',
    handler: function() {
        console.log('Removing the thing')
    }
})

yargs.command({
    command: 'list',
    describe: 'List a thing',
    handler: function(){
        console.log('Listing the thing')
    }
})

yargs.command({
    command: 'read',
    describe: 'Read a thing',
    handler: function(){
        console.log('Reading the thing')
    }
})

console.log(yargs.argv)

 

이렇게 한 다음, node --help 명령어를 실행해 보겠습니다.

$ node app.js --help
app.js [명령]

명령:
  app.js add     Add a new thing
  app.js remove  Remove a thing
  app.js list    List a thing
  app.js read    Read a thing

옵션:
  --help     도움말을 보여줍니다                                          [여부]
  --version  버전 넘버를 보여줍니다  

 

다음으로 app.js의 각 명령문에 builder 를 추가해 줍니다.

const yargs = require('yargs')

yargs.version('1.1.0')

yargs.command({
    command: 'add',
    describe: 'Add a new thing',
    builder: {
        title: {
            describe: 'Thing title'
        }
    }
    handler: function(argv) {
        console.log('Adding a new thing!', argv)
    }
})

yargs.command({
    command: 'remove',
    describe: 'Remove a thing',
    handler: function() {
        console.log('Removing the thing')
    }
})

yargs.command({
    command: 'list',
    describe: 'List a thing',
    handler: function(){
        console.log('Listing the thing')
    }
})

yargs.command({
    command: 'read',
    describe: 'Read a thing',
    handler: function(){
        console.log('Reading the thing')
    }
})

console.log(yargs.argv)

 

그 다음 node 명령문을 실행해 봅니다.

$ node app.js add --title="Shopping list"
Adding a new thing! { _: [ 'add' ], title: 'Shopping list', '$0': 'app.js' }
{ _: [ 'add' ], title: 'Shopping list', '$0': 'app.js' }

이렇게 변경된 결과를 얻을 수 있습니다.

위 명령문에서는 --title 부분이 옵션이라 명시하지 않아도 돌아갑니다.

--title 없이 add만 넣어서 진행해도 다음과 같이 이상없이 돌아가는 것을 확인할 수 있습니다.

$ node app.js add
Adding a new thing! { _: [ 'add' ], '$0': 'app.js' }
{ _: [ 'add' ], '$0': 'app.js' }

 

 

app.js 를 수정해서 title을 필수 요소로 변경해 주겠습니다.

const yargs = require('yargs')

yargs.version('1.1.0')

yargs.command({
    command: 'add',
    describe: 'Add a new thing',
    builder: {
        title: {
            describe: 'Thing title',
            demandOption: true
        }
    }
    handler: function(argv) {
        console.log('Adding a new thing!', argv)
    }
})

yargs.command({
    command: 'remove',
    describe: 'Remove a thing',
    handler: function() {
        console.log('Removing the thing')
    }
})

yargs.command({
    command: 'list',
    describe: 'List a thing',
    handler: function(){
        console.log('Listing the thing')
    }
})

yargs.command({
    command: 'read',
    describe: 'Read a thing',
    handler: function(){
        console.log('Reading the thing')
    }
})

console.log(yargs.argv)

이렇게 변경한다음, node 명령어를 title 없이 실행해 보겠습니다.

$ node app.js add
app.js add

Add a new thing

옵션:
  --help     도움말을 보여줍니다                                          [여부]
  --version  버전 넘버를 보여줍니다                                       [여부]
  --title    Thing title                                                  [필수]

필수 인자를 받지 못했습니다: title

에러가 나는 것을 확인할 수 있습니다.

 

이번에는 node 명령어를 title과 같이 사용하지만 값을 지정하지 않으면 어떻게 되는지 알아보겠습니다.

$ node app.js add --title
Adding a new thing! { _: [ 'add' ], title: true, '$0': 'app.js' }
{ _: [ 'add' ], title: true, '$0': 'app.js' }

title 값이 true로 반환되는 것을 확인할 수 있습니다.

 

 

이번에는 app.js에서 title의 형식을 지정해 보겠습니다.

const yargs = require('yargs')

yargs.version('1.1.0')

yargs.command({
    command: 'add',
    describe: 'Add a new thing',
    builder: {
        title: {
            describe: 'Thing title',
            demandOption: true,
            type: 'string'
        }
    }
    handler: function(argv) {
        console.log('Adding a new thing!', argv)
    }
})

yargs.command({
    command: 'remove',
    describe: 'Remove a thing',
    handler: function() {
        console.log('Removing the thing')
    }
})

yargs.command({
    command: 'list',
    describe: 'List a thing',
    handler: function(){
        console.log('Listing the thing')
    }
})

yargs.command({
    command: 'read',
    describe: 'Read a thing',
    handler: function(){
        console.log('Reading the thing')
    }
})

console.log(yargs.argv)
$ node app.js add --title
Adding a new thing! { _: [ 'add' ], title: '', '$0': 'app.js' }
{ _: [ 'add' ], title: '', '$0': 'app.js' }

이번에는 title 값이 빈칸으로 나타나는 것을 확인할 수 있습니다.

 

이번에는 title 값을 지정해서 실행해보겠습니다.

$ node app.js add --title="This is title"
Adding a new thing! { _: [ 'add' ], title: 'This is title', '$0': 'app.js' }
{ _: [ 'add' ], title: 'This is title', '$0': 'app.js' }

 

결과를 자세히 보면 중복으로 표시되는 부분이 있는데 이경우에는, app.js 파일을 다음과 같이 변경해 주면 한번만 표시되는 것을 확인할 수 있습니다. 

const yargs = require('yargs')

yargs.version('1.1.0')

yargs.command({
    command: 'add',
    describe: 'Add a new thing',
    builder: {
        title: {
            describe: 'Thing title',
            demandOption: true,
            type: 'string'
        }
    }
    handler: function(argv) {
        console.log('Adding a new thing!', argv)
    }
})

yargs.command({
    command: 'remove',
    describe: 'Remove a thing',
    handler: function() {
        console.log('Removing the thing')
    }
})

yargs.command({
    command: 'list',
    describe: 'List a thing',
    handler: function(){
        console.log('Listing the thing')
    }
})

yargs.command({
    command: 'read',
    describe: 'Read a thing',
    handler: function(){
        console.log('Reading the thing')
    }
})

yargs.parse()

맨 마지막에 console.log(yargs.argv)을 yargs.parse()로 변경했습니다.

$ node app.js add --title="This is title"
Adding a new thing! { _: [ 'add' ], title: 'This is title', '$0': 'app.js' }

 

 

이번에는 body 옵션을 넣어보겠습니다.

const yargs = require('yargs')

yargs.version('1.1.0')

yargs.command({
    command: 'add',
    describe: 'Add a new thing',
    builder: {
        title: {
            describe: 'Thing title',
            demandOption: true,
            type: 'string'
        },
        body: {
            describe: 'Thing body',
            demandOption: true,
            type: 'string'
        }
    },
    handler: function(argv) {
        console.log('Title: ' + argv.title)
        console.log('Body: ' + argv.body)
    }
})

yargs.command({
    command: 'remove',
    describe: 'Remove a thing',
    handler: function() {
        console.log('Removing the thing')
    }
})

yargs.command({
    command: 'list',
    describe: 'List a thing',
    handler: function(){
        console.log('Listing the thing')
    }
})

yargs.command({
    command: 'read',
    describe: 'Read a thing',
    handler: function(){
        console.log('Reading the thing')
    }
})

yargs.parse()
$ node app.js add --title="This is title" --body="This is body"
Title: This is title
Body: This is body

 

이렇게 Node.js에서 yargs npm 모듈 사용하는 방법에 대해서 알아보았습니다.

유용하셨다면, 공감과 구독 부탁 드립니다.

감사합니다. :)

댓글