File System And Command Line Args
Command Line Arguments
When you provide arguments to a CLI, Node.js has access to those arguments in the process.argv
array (v stands for vector).
If we want to use our command line arguments to influence the behaviour of our application, we simply create conditional logic!
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
.
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 usingyargs.version("1.1.0");
.To add commands to
yargs
, use theyargs.command
method and pass a configuration object inside. The key property ishandler
, 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.JSON.parse(json);
to convert JSON back to object.Now you can use object in your code!
Last updated