🪴 yshalsager's Digital Garden

Search

Search IconIcon to open search

Node.js yargs package

Last updated Nov 3, 2022

المعرفة:: NodeJS
الحالة:: #ملاحظة_مؤرشفة
المراجع:: The Complete Node.js Developer Course 3rd Edition, coggro’s Notes


# Introduction

# Installing and Setting Up Yargs

1
npm install yargs@12.0.2  
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const yargs = require('yargs')  
  
// Customize version  
yargs.version('1.1.0')  
  
// Add command  
yargs.command({  
	command: 'add',  
	describe: 'Add a new note',  
	handler: function () {  
		console.log('Adding a new note!')  
	}  
})  
  
console.log(yargs.argv)  
1
2
$ node app.js add  
# Adding a new note!  
1
2
3
4
$ node app.js --version  
# 1.1.0  
  
$ node app.js --help  
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
args  
  .command({  
    command: `add`,  
    description: `Add a new note`,  
    handler: () => {  
      console.log(`Adding a new note.`)  
    },  
  })  
  .command({  
    command: `remove`,  
    description: `Remove a note.`,  
    handler: () => {  
      console.log(`Removing a note.`)  
    },  
  })  

# Adding Command Options

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
yargs.command({  
  command: `add`,  
  description: `Add a new note`,  
  builder: {  
    title: {  
      describe: `Note title`, // Describe option for help  
      demandOption: true, // Require option  
      type: `string`, // Force a string value  
    },  
  },  
  // Add argv to arguments here and use in funcution  
  handler: (argv) => {  
    console.log(`Title: ${argv.title}`)  
  },  
})  
1
2
3
$ node app.js add --title="Buy" --body="Note body here"  
Title: Buy  
Body: Note body here