run terminal command from node js linux code example

Example 1: node run shell command

// You can use 'exec' this way

const { exec } = require("child_process");

exec("ls -la", (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});

Example 2: node execute shell commands

const { exec } = require("child_process");
exec("cat index.js", (error, data, getter) => {
	if(error){
		console.log("error",error.message);
		return;
	}
	if(getter){
		console.log("data",data);
		return;
	}
	console.log("data",data);

});

Example 3: how to run js file in node terminal

node FileName.js