NeuroAgent

How to Access Node.js Command Line Arguments

Learn how to access command line arguments in Node.js using process.argv. This complete guide shows how to pass arguments to your Node.js programs and handle them in your code with practical examples.

Question

How do I pass command line arguments to a Node.js program and access them in my code?

I have a web server written in Node.js and I would like to launch it with a specific folder. I’m not sure how to access command line arguments in JavaScript. I’m running Node.js like this:

$ node server.js folder

Here server.js is my server code. According to the Node.js help documentation, this is possible:

$ node -h
Usage: node [options] script.js [arguments]

How would I access those arguments in JavaScript? I haven’t been able to find this information online.

NeuroAgent

To pass command line arguments to a Node.js program and access them in your code, you can use the process.argv array which contains the command line arguments. When running node server.js folder, the argument “folder” will be available in process.argv[2], with the first two elements being the Node.js executable path and the script file name.


Contents


Understanding process.argv

In Node.js, the process.argv array is a built-in global object that contains the command line arguments passed when the Node.js process was launched. This array has a specific structure that’s important to understand:

  • process.argv[0]: The path to the Node.js executable
  • process.argv[1]: The path to the JavaScript file being executed
  • process.argv[2] and beyond: The actual command line arguments passed to the script

Key Insight: The first two elements in process.argv are always reserved for the Node.js executable and the script file name, so your actual arguments start from index 2.

For example, when you run:

bash
node server.js folder

The process.argv array will look like this:

javascript
[
  '/path/to/node',      // Node.js executable
  '/path/to/server.js', // Your script file
  'folder'             // Your first argument
]

Accessing Command Line Arguments

Here’s the fundamental way to access command line arguments in Node.js:

javascript
// server.js
console.log('Total arguments:', process.argv.length);
console.log('All arguments:', process.argv);

// Access individual arguments
const folderArg = process.argv[2]; // This will be 'folder'
console.log('Folder argument:', folderArg);

// You can also use array methods to filter out the first two elements
const userArgs = process.argv.slice(2);
console.log('User arguments:', userArgs);

When you run this with node server.js folder, the output will be:

Total arguments: 3
All arguments: [ '/path/to/node', '/path/to/server.js', 'folder' ]
Folder argument: folder
User arguments: [ 'folder' ]

Practical Example: Server with Folder Path

Here’s how you can implement your specific use case of launching a web server with a specific folder:

javascript
// server.js
const http = require('http');
const fs = require('fs');
const path = require('path');

// Get the folder argument from command line
const folderPath = process.argv[2];

// Validate that a folder was provided
if (!folderPath) {
  console.error('Error: Please provide a folder path as argument');
  console.log('Usage: node server.js <folder-path>');
  process.exit(1);
}

// Check if the folder exists
if (!fs.existsSync(folderPath)) {
  console.error(`Error: Folder "${folderPath}" does not exist`);
  process.exit(1);
}

// Create HTTP server
const server = http.createServer((req, res) => {
  const filePath = path.join(folderPath, req.url);
  
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end('File not found');
    } else {
      res.writeHead(200);
      res.end(data);
    }
  });
});

// Start server on port 3000
const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
  console.log(`Serving files from: ${path.resolve(folderPath)}`);
});

To use this server:

bash
node server.js /path/to/your/folder

Advanced Argument Parsing

While process.argv works for simple cases, more complex applications benefit from dedicated argument parsing libraries. Here are popular options:

Using yargs

bash
npm install yargs
javascript
const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');

const argv = yargs(hideBin(process.argv))
  .option('port', {
    alias: 'p',
    type: 'number',
    description: 'Port to run the server on',
    default: 3000
  })
  .option('folder', {
    alias: 'f',
    type: 'string',
    description: 'Folder to serve files from',
    demandOption: true
  })
  .help()
  .alias('help', 'h')
  .argv;

console.log('Server configuration:', {
  port: argv.port,
  folder: argv.folder
});

Usage:

bash
node server.js -f /path/to/folder -p 8080

Using Commander

bash
npm install commander
javascript
const { program } = require('commander');

program
  .requiredOption('-f, --folder <path>', 'Folder to serve files from')
  .option('-p, --port <port>', 'Port to run the server on', '3000')
  .parse();

console.log('Server configuration:', program.opts());

Best Practices and Error Handling

When working with command line arguments, follow these best practices:

1. Validate Input

Always validate arguments before using them:

javascript
const folderPath = process.argv[2];

if (!folderPath) {
  console.error('Error: Folder path is required');
  process.exit(1);
}

// Check if it's a valid path
const fs = require('fs');
if (!fs.existsSync(folderPath)) {
  console.error(`Error: Path "${folderPath}" does not exist`);
  process.exit(1);
}

// Check if it's a directory
if (!fs.statSync(folderPath).isDirectory()) {
  console.error(`Error: "${folderPath}" is not a directory`);
  process.exit(1);
}

2. Provide Usage Instructions

Help users understand how to use your script:

javascript
if (process.argv.includes('--help') || process.argv.includes('-h')) {
  console.log(`
Usage: node server.js [options]

Options:
  -f, --folder <path>    Folder to serve files from (required)
  -p, --port <port>      Port to run the server on (default: 3000)
  -h, --help             Show this help message

Examples:
  node server.js -f /var/www
  node server.js --folder /var/www --port 8080
`);
  process.exit(0);
}

3. Handle Different Argument Types

javascript
const args = process.argv.slice(2);

// Find specific arguments
const folderArg = args.find(arg => !arg.startsWith('-'));
const portArg = args.find(arg => arg.startsWith('--port')) || 
                args.find(arg => arg.startsWith('-p'));

const folderPath = folderArg || '/default/path';
const port = portArg ? parseInt(portArg.split('=')[1]) || parseInt(portArg.split(' ')[1]) : 3000;

Environment Variables Alternative

For sensitive configuration or when you prefer not to pass arguments directly, consider using environment variables:

javascript
// server.js
const folderPath = process.env.SERVER_FOLDER || process.argv[2];
const port = process.env.SERVER_PORT || 3000;

// Usage:
// With arguments: node server.js /path/to/folder
// With environment variables: SERVER_FOLDER=/path/to/folder node server.js

Conclusion

Accessing command line arguments in Node.js is straightforward using the process.argv array, with the actual arguments starting from index 2. For your web server use case, you can extract the folder path with process.argv[2] and use it to configure your file serving functionality.

Key takeaways:

  1. Use process.argv.slice(2) to get only the user-provided arguments
  2. Always validate arguments before using them to prevent errors
  3. Consider using argument parsing libraries like yargs or commander for complex applications
  4. Provide clear usage instructions and error messages for better user experience
  5. Environment variables offer an alternative approach for configuration

For most simple applications like your web server, the basic process.argv approach will work perfectly. However, as your application grows in complexity, investing in a proper argument parsing library will save you time and provide better user experience.