Node.js Execute a Unix Command

Posted on March 18, 2017 at 11:35 pm

Use child_process.exec to execute a comand and fetch its output:

var exec = require('child_process').exec;
var cmd = 'id';
exec(cmd, function(error, stdout, stderr) {
    console.log("Output: "+stdout);

Or you can use execFile() method:

var execFile = require('child_process').execFile;
execFile("/bin/ls", ['-la'], function(error, stdout, stderr) {
  console.log("Output: "+stdout);

Run Unix commands on the Node.js server remotely:

var dns = require("dns");
var exp = require("express");
var app = exp();
var exec = require('child_process').exec;
app.get("/exec/:command", function (req, res) {
    var command = req.params.command;
    exec(command, function (error, stdout, stderr) {
        if (error === null) {
            res.header("Content-Type", "application/json");
	    res.end(JSON.stringify(stdout, null, "\t"), "utf-8");
console.log("Now go visit `` from your browser...");

Obviously it is dangerous to allow anyone to execute any command.

This was created only for testing purposes!

You can run Unix commands on the Node.js server:

More information here:
Execute a command line binary with Node.js

Updated on September 6, 2019 at 10:49 am

Receive updates via email

Other Posts

Updated Posts