General Middleware

NodeJS exec() command for both Windows and Linux

Use the below code for NodeJS exec() command for both Windows and Linux. As a first step, download the ‘child_process’ and ‘os’ modules.

npm install child_process
npm install os
const { exec } = require('child_process')
const os = require('os')

const executeCommand = (req, res, next) => {
    var COMMAND = ''
    const platform = os.platform()
    switch(platform) {
        case 'linux': 
            COMMAND = "ls /tmp"
            break;
        case 'win32':
            COMMAND = "dir /D ."
            break;    
        default: console.log("unknown platform");
        return
    }

    exec(COMMAND, (error, stdout, stderr) => {
        if (error == null && stderr === '') {

           console.log("Output from commands = ",stdout)
        }
    })
}
module.exports = executeCommand 

Leave a Reply

Your email address will not be published. Required fields are marked *