Command Line Arguments

 


'use strict';

/* Command Line Arguments */
// [0] The path of the executable that started the Node.js process
// [1] The path to this application
// [2-n] the command line arguments

console.log(process.argv);


Output:- 



Get arguments 


'use strict';

// Set first argument as username.
var username = process.argv[2];
// Check if the username hasn't been provided.
if (!username) {

    // require('path').sep    Provides the platform-specific path segment separator  LINK :- https://nodejs.org/api/path.html#pathsep

    /*The split() method
        splits a string into an array of substrings.
        returns the new array.
        does not change the original string.
        If (" ") is used as separator, the string is split between words.
    */

    // Extract the filename
    var appName = process.argv[1].split(require('path').sep).pop();

    // Give the user an example on how to use the app.
    console.error('Missing argument! Example: %s YOUR_NAME', appName);

    process.exit(1);
    // Exit the app (success: 0, error: 1).
}
else
{
    // Print the message to the console.
    console.log('Hello %s!', username);
}


OUTPUT:- 

PS E:\node_server> node .\server.js pradipta paul 25 28
Hello pradipta!
PS E:\node_server>


Comments