calling child_process.exec in Node as though it was executed in a specific folder - node.js

I'm using the following to execute a CLI command in nodeJS
var cp = require('child_process');
cp.exec('foocommand', callback);
However, the foocommand is executing in the current folder node is running from. How can I make it execute as though it is being invoked from a different folder?

Its in the docs:
var cp = require('child_process');
cp.exec('foocommand', { cwd: 'path/to/dir/' }, callback);

Not a total expert but if its a cli then you want to be able to use stdin witch is not available with process.exec. Maybe you want to see if there is a programable interface for the cli?

Related

Executing Command in Nodejs and Attaching the output to the console

I'm working on a CLI tool to add an extra layer of automation and utilities to our workflow and I'm wrapping the webpack development command with an alternative in my CLI (here's a demonstration):-
function runDev(){
this.doSomePreAutomationAndPreperations();
this.runWebpackDevCommand();
}
I'm using NodeJs child_proecess.exec and I'm trying to figure out a way to execute the webpack dev command and attach it to the terminal (like -it in docker if you're familiar with it) or transferring the control to the child process(so output will be directly emitted to the console).
Is there away to do that?
It turns out that I can achieve this but just making the child process inherit the stdio. ex:-
const { spawn } = require('child_process')
const shell = spawn('sh',[], { stdio: 'inherit' })
shell.on('close',(code)=>{console.log('[shell] terminated :',code)})

Installing NPM Modules via the Frontend

I am working on an app wherein I would like to be able to install NPM modules via the frontend. I have no idea, though, how to do so. That is, I know how to do CRUD actions via the front end, but I don't know how to either interact with the command line or run command line functions via the front end.
Are there packages that can help with this or is this built into Node.js somehow?
In short, how can I connect my front-end to my backend in such a way that I can install an NPM package?
What you want is the child_process module. It's built-in so you don't need to install any additional module.
Mostly what you're looking for is either spawn() or exec().
For example, if you want to run npm install some_module you can do:
const { exec } = require('child_process');
let command = 'npm install some_module';
let options = { cwd: '/path/to/node/project' };
exec(command, options, (error, stdout, stderr) => {
// Do anything you want with program output here:
console.log('output:', stdout, stderr);
});
You may check the documentation for child_process in Node JS:
Child Process
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
The key difference between exec() and spawn() is how they return the data. As exec() stores all the output in a buffer, it is more memory intensive than spawn(), which streams the output as it comes.
Generally, if you are not expecting large amounts of data to be returned, you can use exec() for simplicity. Good examples of use-cases are creating a folder or getting the status of a file. However, if you are expecting a large amount of output from your command, then you should use spawn()
The easiest way to install an npm package via "the front end" is to have node spawn npm as a child process based off of the package name that the client provides.
var child = require('child_process').exec(`npm i ${package_name}`);
child.on('exit',function(){
//npm finished
});
This should install the module given that package_name is the name of the npm package, in the same directory that the script is running in. In terms of getting the package name from the front end to the back end, there are several different ways to do that.
You cannot run the your backend application without NPM modules installed, one thing that I think you can do is to make a plain nodejs file without any modules, which will receive the args when invoked, and you can use that args to the required modules, because that file will run with just core modules

Im trying to reduplicate the shelljs exec type execution in node

I was using shelljs before where i used to call a command like so:
require('shelljs/global');
let res = exec('echo hello').stdout
But I would like to achieve this in node without relying on shelljs.
Thing is I've found examples with node and I'm having trouble with quite a few of them.
Thanks for the help
The ultra simple answer is use the synchronous version of exec. The stdout won't appear as the command runs and the result won't have the nice properties shelljs provides, just the stdout data
const { execSync } = require('child_process')
const exec = (cmd) => execSync(cmd).toString()
const res = exec('echo "hello there"')
The full shelljs implementation is in exec.js, which runs the command via exec-child.js script to enable the live output + capture to variables for a synchronous exec. It depends on the features you require as to how complex the solution becomes.

How to create and manage a npm process in electron

I'm trying to make this little QoL app that can trigger my scripts inside package.json of any project I throw at it (react, polymer, etc.).
So far, it works as it should. At least until I kill the app or want to terminate the specific process (like using ctrl+c while running a npm start in a console).
I'm currently calling the command this way:
const exec = require("child_process").execFile;
...
let ps = exec("command.bat", [path, command], (error, stdout, stderr)=>{}) //command.bat contains only: cd "%1" \n npm "%2"
Previously I've used node-powershell like so:
const Shell = require('node-powershell');
...
let sh = new Shell();
sh.addCommand(`cd ${fs.realpathSync(path)}`);
sh.addCommand(`npm ${command}`);
sh.invoke();
And I've already tried using ps-tree in hopes that this will list all the processes started by my process so I can kill them but no luck and because it creates additional process or two it's getting out of hands really quickly.
const cp = require('child_process');
...
psTree(ps.pid, function (err, children) {
cp.spawn('kill', ['-9'].concat(children.map(function (p) { return p.PID })));
});
So if there is some solution I would be really grateful. I'm also open to any different solution if there is any.
Thanks in advance.

node.js child process change a directory and run the process

I try to run external application in node.js with child process like the following
var cp = require("child_process");
cp.exec("cd "+path+" && ./run.sh",function(error,stdout,stderr){
})
However when I try to run it stuck, without entering the callback
run.sh starts a server, when I execute it with cp.exec I expect it run asynchronously, such that my application doesn't wait until server termination. In callback I want to work with server.
Please help me to solve this.
cp.exec get the working directory in parameter options
http://nodejs.org/docs/latest/api/child_process.html#child_process_child_process_exec_command_options_callback
Use
var cp = require("child_process");
cp.exec("./run.sh", {cwd: path}, function(error,stdout,stderr){
});
for running script in the "path" directory.
The quotes are interpreted by the shell, you cannot see them if you just look at ps output.

Resources