However, process.argv isn't great at parsing strings, especially when we use flags. In order to parse strings to use flags in our commands, we can import modules like yargs.
// In console: node app.js add --title="New Note"console.log(process.argv[3]);// Logs "--title='New Note'" as one long stringconstyargs=require("yargs");console.log(yargs.argv.title);// Logs "New Note"
Yargs tips
By default, modules like yargs provide a --help flag showing other available flags. One other default flag is --version, which starts at v1.0.0. You can update this using yargs.version("1.1.0");.
To add commands to yargs, use the yargs.command method and pass a configuration object inside. The key property is handler, which runs the callback you provide when the command is invoked.
yargs.parse() must appear the bottom of your code in order for anything to appear on your command line.
Storing Data in JSON
Now that we can obtain inputs using yargs and the command line, how do we store that data? Basic answer is to use the fs (file system) built-in Node.js module. One format we can store data in is JSON.
JSON is just a string. JavaScript provides the JSON API to easily convert JS objects to and from JSON. (JSON.stringify converts objects to JSON. JSON.parse converts JSON to objects.)
Using the fs module, we can perform the following steps to write data into JSON and then read from it.
Create a JS object.
JSON.stringify(obj); to convert to JSON.
fs.writeFileSync("file.json", json); to write JSON string to file.
const dataBuffer = fs.readFileSync(file.json); to return a data buffer (it's bytes, not strings).
dataBuffer.toString(); to convert data buffer to JSON string.