Page Content

Tutorials

What is the OS Module of NodeJS? Explained with Code

OS Module of NodeJS

One of Node.js’s essential built-in core modules, the OS module offers a number of useful techniques for communicating with the computer and operating system that your program is executing on. To incorporate its functionality into your application, you can utilise the require function instead of installing it separately.

This module is quite helpful for getting different bits of information that are specific to the system. For example, it can be used to find the line delimiter sequence (os.EOL), which is \n on Linux and macOS, and \r\n on Windows. The constants for process signals (os.constants.signals) and error reporting (os.constants.errno) are also provided.

The following are a few of the main techniques the OS module offers:

  1. os.arch(): Returns a string identifying the underlying architecture, such as arm or x64.
  2. os.cpus(): Provides detailed information about the CPUs available on your system, including model and speed.
  3. os.freemem(): Indicates the amount of free memory in bytes.
  4. os.homedir(): Returns the path to the current user’s home directory.
  5. os.hostname(): Gives you the hostname of the system.
  6. os.platform(): Identifies the operating system platform, like darwin for macOS or win32 for Windows.
  7. os.totalmem(): Returns the total memory available in the system, in bytes.
  8. os.type(): Identifies the operating system, e.g., Linux, Darwin (macOS), or Windows_NT.
  9. os.uptime(): Returns the number of seconds the computer has been running since its last reboot.

One especially useful function is os.userInfo(), which lets you retrieve a number of facts about the user who is presently logged in, including their username. Customising programs or recording user-specific activity can benefit greatly from this.

Below is a little example showing how to use the OS module to get the username of the current user and add it to a file:

const os = require('os'); 
const fs = require('fs'); 
// Get user information
const user = os.userInfo(); 
// Define the filename and content
const filename = 'greeting.txt';
const content = `Hello ${user.username}! Welcome to your Node.js app.`; 
// Append content to the file
fs.appendFileSync(filename, content); 
console.log(`Greeting written to ${filename} for user ${user.username}.`);

Getting Input from Users (Command-Line Arguments)

Getting user feedback is crucial for any real-world setup. Arguments that can change the behaviour of Node.js command-line tools are frequently accepted. Throughout the process, Node.js offers an integrated method to retrieve these command-line process.argv array.

The process.argv array has a specific structure:

  • The first element (process.argv) is always the full path to the Node.js executable that started the process.
  • The second element (process.argv) is the full path to the JavaScript file being executed.
  • All subsequent elements (process.argv onwards) are the actual command-line arguments provided by the user.

To retrieve just the arguments entered by the user, you can use the slice() method on the process.argv array, starting from index 2.

This is an illustration of how to use process.argv to obtain and handle fundamental command-line arguments:

// Access the full process.argv array
console.log('Full process.argv array:', process.argv); 
// Get only the user-provided arguments
const userArgs = process.argv.slice(2); 
console.log('User-provided arguments:', userArgs);
if (userArgs.length > 0) {
    const command = userArgs; 
    console.log(`The command received is: ${command}`);
    if (command === 'add') {
        console.log('Adding a note!');
    } else if (command === 'remove') {
        console.log('Removing a note!'); 
    } else {
        console.log('Unknown command.');
    }
} else {
    console.log('Please provide a command (e.g., add, remove).');
}

If you run this script from your terminal like node app.js add my note, you’ll see how process.argv contains the full path to node, then app.js, followed by 'add' and 'my', and 'note' as user arguments. While process.argv is fundamental, manually parsing more complex arguments, especially key-value pairs (--title="My Title"), can quickly become cumbersome and prone to errors. This is where yargs comes in.

Argument Parsing with Yargs

A strong third-party npm module called yargs was created to make it easier for Node.js apps to parse command-line arguments. It improves the readability and cleanliness of your code by eliminating the need to manually create parsers for complicated arguments.

Installing yargs using npm is a prerequisite for using it. Including it in your package as a dependent is a smart package.json document:

npm install yargs --save

After installation, yargs may be require to define the commands and options of your application using its API and required in your Node.js code. yargs takes the unprocessed approach.parses the argv array and returns a much more useful object, which is frequently available through yargs.argv.

Some of the main characteristics of yargs for defining arguments are as follows:

  1. yargs.version(): Allows you to set a version number for your command-line tool, which users can query with --version.
  2. yargs.command(): Enables you to define distinct commands for your application (e.g., add, remove, list, read for a note-taking app). Each command can have its own description and a handler function that executes when the command is invoked.
  3. builder property: Within yargs.command(), the builder property is an object where you define the specific options or arguments for that command. For example, a note add command might require a title and a body.
  4. Option properties: Inside the builder, each option can have properties such as:
    • describe: A string providing a description of what the option is for.
    • demandOption: A boolean that, if true, makes the option required for the command to run successfully.
    • type: Specifies the expected data type of the option’s value (e.g., 'string').
    • alias: A single character or short string alias for the option (e.g., -t for --title).
  5. yargs.help(): When the user enters --help, yargs.help() automatically creates and presents thorough help documentation for your program, including all defined commands and their arguments.

Allowing users to write notes with a title and body, let’s see an example of how to configure commands and options for a note-taking application using yargs:

const yargs = require('yargs'); 
// Configure yargs to set a version 
yargs.version('1.1.0');  
// Add 'add' command with required title and body options 
yargs.command({
    command: 'add', 
    describe: 'Add a new note', 
    builder: { 
        title: {
            describe: 'Note title', 
            demandOption: true, // Make title required 
            type: 'string', // Ensure title is a string 
            alias: 't' // Shorthand for title 
        },
        body: {
            describe: 'Note body'
            demandOption: true, // Make body required 
            type: 'string', // Ensure body is a string 
            alias: 'b' // Shorthand for body 
        }
    },
    handler: function (argv) { 
        console.log('Adding a new note!');
        console.log(`Title: ${argv.title}`); // Access parsed title 
        console.log(`Body: ${argv.body}`); // Access parsed body 
    }
});
// Add 'list' command (no arguments required) 
yargs.command({
    command: 'list'
    describe: 'List all notes'
    handler: function () {
        console.log('Listing all notes...');
    }
});
// Add 'remove' command with required title option
yargs.command({
    command: 'remove'
    describe: 'Remove a note'
    builder: {
        title: {
            describe: 'Note title'
            demandOption: true, // Required 
            type: 'string', // String type 
            alias: 't' // Shorthand 
        }
    },
    handler: function (argv) {
        console.log('Removing note:', argv.title); 
    }
});
// Call .help() to enable auto-generated documentation for commands 
yargs.help(); 
// Parse the arguments that were passed in 
yargs.parse();

The following commands could be used to test this enhanced argument parsing:

  • node app.js add --title="Grocery List" --body="Milk, Eggs, Bread"
  • node app.js add -t="Meeting Notes" -b="Discuss Q3 results" (using aliases)
  • node app.js list
  • node app.js remove --title="Grocery List"
  • node app.js --help (to see the auto-generated documentation for all commands and their options)

As you can see, yargs turns jumbled command-line strings into a tidy, easily readable object, which greatly simplifies the writing and maintenance of your application’s logic. Like having a specialist interpreter at the program’s entry, it makes sure all of the messages arrive in an orderly and understandable format before your primary logic has a chance to act upon them.

Index