How to create and manage a npm process in electron - node.js

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.

Related

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

Npm child process live feed

I am writing a CLI tool for a node.js app. Some of the commands have to run npm and show the results. This is what I have so far:
import {spawn} from 'child_process';
let projectRoot = '...';
let npm = (process.platform === "win32" ? "npm.cmd" : "npm"),
childProcess = spawn(npm, ["install"], { cwd: projectRoot });
childProcess.stdout.pipe(process.stdout);
childProcess.stderr.pipe(process.stderr);
childProcess.on('close', (code) => {
// Continue the remaining operations
});
The command does run fine and outputs the results (or errors). However, it doesn't give me a live feed with the progress bar, etc. It waits until the entire operation is over and then dumps the output into the console.
I've tried different variations of the spawn configuration but I can't get it to show me the live feed.
I am on Windows 10 and use node.js 4 and npm 3.
As discussed in the comments: Run the spawn with { stdio: 'inherit' }.
However, good question is why the 'manual piping' does not do the same. I think that's because npm uses the 'fancy progress bar'. It probably uses some special way how to deal with stdout that does not play well with process.stdout. If you try some other long-running command (such as 'find ./'), your way of piping works fine.

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.

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

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?

Equivalent of Rake's 'sh' for Jake?

I've got some experience with Ruby and Rake, but now I'm working on a Node project and want to learn how to do the same things with Jake.
Ruby has a system function that will shell out to a command and wait for it to exit. Rake extends this by adding an sh function that will additionally throw an error if the child process returned a nonzero exit code (or couldn't be found at all). sh is really handy for Rake tasks that shell out to things like compilers or test frameworks, because it automatically terminates the task as soon as anything fails.
Node doesn't seem to have anything like system or sh -- it looks like the nearest equivalents are child_process.spawn and child_process.exec, but neither of them wires up STDOUT or STDERR, so you can't see any output from the child process unless you do some extra work.
What's the best way to get an sh method for Jake? (Though since this is Node, I'd expect it to be async, rather than blocking until the command returns like Ruby does.) Is there an npm module that has already invented this particular wheel, or does someone have a code sample that does this?
I've already seen sh.js, but it looks awfully heavyweight for this (it tries to build an entire command interpreter in Node), and it doesn't look like it's async (though the docs don't say one way or the other).
I'm looking for something that I could use more or less like this (using Jake's support for async tasks):
file('myprogram', ['in.c'], function() {
// sh(command, args, successCallback)
sh('gcc', ['in.c', '-o', 'myprogram'], function() {
// sh should throw if gcc couldn't be found or returned nonzero.
// So if we got here, we can tell Jake our task completed successfully.
complete();
});
}, true);
Here's some code I've come up with that seems to work well. (But if anyone has a better answer, or knows of an existing npm module that already does this, please add another answer.)
Supports full shell syntax, so you can use | and < and > to pipe and redirect output, you can run Windows batch files, etc.
Displays output (both STDOUT and STDERR) as the child process generates it, so you see incremental output as the command runs.
No limitation on the amount of output the command can generate (unlike a previous exec-based version of this code).
Cross-platform (works on Windows, should work on Mac/Linux as well). I borrowed the platform-specific-shell (if platform === 'win32') technique from npm.
Here's the code:
function sh(command, callback) {
var shell = '/bin/sh', args = ['-c', commandLine], child;
if (process.platform === 'win32') {
shell = 'cmd';
args = ['/c', commandLine];
}
child = child_process.spawn(shell, args);
child.stdout.pipe(process.stdout);
child.stderr.pipe(process.stderr);
child.on('exit', function(code, signal) {
if (signal != null)
throw new Error("Process terminated with signal " + signal);
if (code !== 0)
throw new Error("Process exited with error code " + code);
callback();
});
};

Resources