Execute Command from Node JS


The command ls [directory] prints the contents of a directory. If the directory argument is not specified it will print the contents of the current working directory.

First, we will import the fs module at the top of the file. The fsmodule is the Node.js core module for file system operations.

var fs = require('fs');

To implement ls, add a new property to our commands object named 'ls':

var commands = {
	'pwd': function () {
		console.log(process.cwd());
	}, 
	'ls': function (args) { // New property added here.
		fs.readdir(args[0] || process.cwd(), function (err, entries) {
			entries.forEach(function (e) {
			console.log(e);
			});
		});
	}
};

Let's talk for a moment about args[0] || process.cwd():

Unlike many other languages, JavaScript doesn't care if you access an index out of bounds of an array. If an element does not exist at the requested index, undefined will be returned. Since undefined is considered false, Using the x || y syntax will test the existence of x and if it is false (doesn't exist), it will evaluate to y. This is a common pattern for assigning a default value.

var fs = require('fs');
var commands = {
	'pwd': function () {
		console.log(process.cwd());
	},
	'ls': function (args) {
		fs.readdir(args[0] || process.cwd(), function (err, entries) {
			entries.forEach(function (e) {
			console.log(e);
			});
		});
	}
};

process.stdin.on('data', function (input) {
	var matches = input.toString().match(/(\w+)(.*)/);
	var command = matches[1].toLowerCase();
	var args = matches[2].trim().split(/\s+/);
	commands[command](args);
});

Just enter command which you want to get info and implement that. Have a look sample output
F:\nodejs\NodeJsPract>node commands.js
ls
	commands.js
	hello.js
	standardInput.js