Reputation: 65
I've am totally newbie when it comes for nodejs.
I am writing a custom program, and I need to add a watch in it, for example I start with nodejs a .bat file which is working fine, but I've been wondering is it possible to control execution of commands in that shell process from the outside?
Like I am running the shell process and type in it by hand "refresh; reload resource_1" and it is working properly, but working with nodemon I would like to add a watch for it, example: I edit a file in a src folder, I would like nodejs automatically to type (or execute) into that shell process the "refresh; reload resource_1" and etc. I tried with exec, but it's working with already defined commands like 'kill, dir' and so more.
I am working on a Windows machine.
Thanks in advance.
Upvotes: 0
Views: 1026
Reputation: 29012
You can write into the child process' stdin
! (Provided that you started it in your own node script.)
const { spawn } = require('child_process')
const child = spawn('some_command') // Start whatever process you want to talk to
// Pipe output so you can see it (you can also instead listen on the stdout/stderr streams
// and capture their output programmatically)
child.stdout.pipe(process.stdout)
child.stderr.pipe(process.stderr)
// Set encoding for input
child.stdin.setEncoding('utf-8')
// Write stuff into the process' stdin!
child.stdin.write('refresh; reload resource_1')
// Note that as long as the process is running and you keep the `child` variable around,
// you can keep writing into `child.stdin` even much later.
Further reading:
If you didn't start the program yourself but you want to automate an already-running program from before, it gets a lot more tricky, and nodejs isn't the best tool for that. There are WinAPI functions you could use but this is its own rabbit hole and it would be a waste of time now to get into it unless you really need it.
Upvotes: 1
Reputation: 2166
You can take advantage of the in-built child_process
of Node.js
'use strict';
//Dependencies
const { exec, sapwn } = require('child_process');
//The command which you wish to run
//If you want to use PowerShell
//child = spawn("powershell.exe",["c:\\temp\\helloworld.ps1"]);
exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
//Logging
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
Please refer to the official documentation here: https://nodejs.org/api/child_process.html
Upvotes: 0