In my Node.js program, I would like to know if a specific port is used so I execute the command below with child_process.exec (example with port 3001) :
netstat -na | find "3001"
If the port is used I get informations about the port as expected but If it is not used I get the following error:
I don't understand why I get this error because when I run the same command in cmd, If the port is not used it doesn't throw error:
Can anyone please tell me what's wrong ?
Node version: v10.16.0
I think you should try this. I have created API you can directly call.
This will return the result data.
const { exec } = require("child_process");
function os_func() {
this.execCommand = function(cmd, callback) {
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
callback(stdout);
});
}
}
app.get("/", (req, res) => {
console.log("inside get");
var os = new os_func();
os.execCommand('netstat -na | find "3001"', function (returnvalue) {
res.end(returnvalue)
});
});
Related
I am trying to run a bash command through Angular.
After some research i found the code below that should be working
import { ChildProcess, exec } from 'child_process';
#Injectable({
providedIn: 'root'
})
export class CommandService {
runCommand(command: string): Promise<string> {
return new Promise((resolve, reject) => {
exec(command, (error: Error, stdout: string, stderr: string) => {
if (error) {
reject(error);
}
resolve(stdout);
});
});
}
}
then i call it in my .ts file
import { CommandService } from './command.service';
export class YourComponent {
output: string;
constructor(private commandService: CommandService) {}
run() {
this.commandService.runCommand('ls -la')
.then(output => this.output = output)
.catch(error => console.log(error));
}
The problem is that even though there doesnt seem to have any errors, when i try to run it it says:
error TS2307: Cannot find module 'child_process' or its corresponding type declarations.
3 import { ChildProcess } from "child_process";
, even though i can see that the file exists in my project.
Is there something i can do to fix that ? If not can i run a command some other way through Angular ?
Thanks in advance
I afraid you can't do that dave Jason.
child_process is available in a nodeJS runtime and Angular runs in a browser. That's 2 different runtimes which only have in common to use JS as a language.
Also, don't expect to be able to run a bash command from the browser that would be a MASSIVE security issue.
Matthieu Riegler is right, you cannot access OS features from within the browser environment. That being said, depending on what you want to do, you could have the bash command run at build time (e.g. with an npm script) or if you really need it at run time and happen to have a backend as well, you could expose an endpoint that runs the bash command on demand and return the result over http.
For anyone who might come to this question for answers:
it's better to use Nodejs (backend) for bash commands.
an example of what i was trying to do is shown in the code below :
onst express = require("express");
const { exec, execSync } = require("child_process");
const cors = require("cors");
const path = require("path");
const app = express();
app.use(
cors({
origin: "http://localhost:4200",
})
);
app.get("/ls", (req, res) => {
exec("ls -la .", (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return res.status(500).send({ error });
}
res.send({ output: stdout });
});
});
const homeDirectory = execSync("echo ~").toString().trim();
const frontendPath = path.join(homeDirectory, "frontend-software");
process.chdir(frontendPath);
exec("ng serve --open", (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
The 1st exec is an ls call and the 2nd is to run an angular project.
Hope it helps you all!
I am trying to open file via node application for which I have used below code.
const app = express()
const port = 3000
const { exec } = require('child_process');
//var exec = require( 'child_process' ).exec;
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
// console.log(`Example app listening at http://localhost:${port}`)
try{
console.log("yet to exec");
exec( "C:/Windows/System32/RunDLL32.exe SHELL32.DLL,ShellExec_RunDLL ?0x8100? 'C:\Users\USER_NAME\.TEMPFOLDER\ID\0\0-999\373\S\v4\SAMPLE.doc'",
{}, function(error){
console.log("Error: "+error);
});
}catch(ex){
console.log("ex: "+ex);
}
})
I am using exec method in child_proccess library to do this task. But the file is not opening also, I am not getting any error both in error callback also, no exception occurs. I have also checked the event viewer of the system but found no issue log regarding this. But, I can able to open the file using the same command via command prompt. It would be helpful if anybody help me to solve this issue. Thanks in advance.
Even with the child_process's methods you could use any program(binary), as you are using Nodejs which is multiplatform, i would recommand you to stick with it.
Let me give you an exemple with Nodejs and 'exec'.
The first argument is the binary(or the access to the binary) of the program you want to use, so for Node it will be node (but we will use the direct path to it process.execPath).
The second argument for Nodejs is -e(execute) or -p(print), that is the basic of Nodejs when you use the Node cli.
The third argument will be the Node command, as you run the Node binary you have direct access to all Node's core-modules, so to read a file we use the fs module.
The exec function return a Callback spliting out an err, stdout and stderr.
See the command
// __filename point to the current file, build your path and replace it with
exec(
`${process.execPath} -p "fs.readFileSync('${__filename}')"`,
(err, stdout, stderr) => {
if(err) console.log(err)
// the stdout is a buffer(binary format), toString() to encode utf8
console.log(stdout.toString())
}
)
My bash emulator can run curl command correctly. But when I call it within nodejs with child_process module, I get an error refering to Protocol "'https" not supported or disabled in libcurl.
When I run "curl 'https://ehire.51job.com/Candidate/SearchResumeNew.aspx'" I can get a page content.
Here's the nodejs code below:
var child_process = require("child_process");
var curl = "curl 'https://ehire.51job.com/Candidate/SearchResumeNew.aspx'";
var child = child_process.exec(curl, (err, stdout, stderr) =>
{
console.log(stdout);
console.log(err);
console.log(stderr);
});
screenshot
Referencing this, exchanged the double quotes with single quotes and vice-versa, the following code works:
var child_process = require("child_process");
var curl = 'curl "https://ehire.51job.com/Candidate/SearchResumeNew.aspx"';
var child = child_process.exec(curl, (err, stdout, stderr) =>
{
console.log(stdout);
console.log(err);
console.log(stderr);
});
I have a NodeJs application running in the following directory
First Application's Path '/users/user1/projects/sampleProject' which is running at 3000 port.
Second Application's Path '/users/user1/demoProjects/demo1' which is going to run at 5000 port on triggering the router function from first application.
The second NodeJs application is not yet started(It will run at port 5000). It need to run independently on hitting a router function in the first NodeJs Application which is running on port 3000 ie(http://localhost:3000/server/startServer). I'm new to NodeJs child processes, Kindly correct me if i'm wrong. And suggest me a right way to do it. Thanks
Start another node application using node.js?
I have tried it like below
// First NodeJs application
import { exec } from "child_process";
router.get('/startServer', async (req, res, next) => {
console.log("Initiated request")
let startServerInstance = 'cd "/users/user1/demoProjects/demo1" && npm run dev'; // path for the second NodeJs application
console.log("Server instance path => " + startServerInstance)
try {
// exec from child process, Spawns a shell then executes the command within that shell
let child = exec(startServerInstance, function (err, stdout, stderr) {
if (err) throw err;
else {
console.log("result ")
res.json({
status: 'success'
});
}
});
} catch (error) {
res.json({
status: 'error',
message: error
});
}
});
The above code executes the command and triggered the second application to run in background but it doesn't return anything. Either error or success result.
You need to use stout and stderror to check other server logs. Also your code is not correct. If you use if without {} it will not go to else statement. That is why you don't see 'result' text in console.
import {
exec
} from "child_process";
router.get('/startServer', async (req, res, next) => {
console.log("Initiated request")
let startServerInstance = 'cd "/users/user1/demoProjects/demo1" && npm run dev'; // path for the second NodeJs application
console.log("Server instance path => " + startServerInstance)
try {
// exec from child process, Spawns a shell then executes the command within that shell
let child = exec(startServerInstance, function(err) {
if (err) throw err;
console.log("Server started");
});
child.stdout.on('data', (data) => {
// this is new server output
console.log(data.toString());
});
child.stderr.on('data', (data) => {
// this is new server error output
console.log(data.toString());
});
res.json({
status: 'success'
});
} catch (error) {
res.json({
status: 'error',
message: error
});
}
});
Child process callback is only called once the process terminates. If the process keeps running, callback is not triggered.
Explained here - https://nodejs.org/docs/latest-v10.x/api/child_process.html#child_process_child_process_exec_command_options_callback
So I have a website with a member area. That member area is managed through a payment processor called CCBill. In order for CCBill to manage a password file on my server, they need to execute a cgi script.
Right now, I've looked at cgi and serve-cgi npm modules. But I'm not sure if they can do what I need. Can anyone help me with this?
My Express Router get function:
router.get('*', function(req, res, next) {
console.log('in');
var mPath = path.join(appRoot, '/cgi-bin' + req.params[0]);
console.log(mPath);
const execFile = require('child_process').execFile;
const child = execFile(mPath, function(error, stdout, stderr) {
if (error) {
console.log(error);
throw error;
}
console.log(stdout);
});
});
Scripts (and other executables) can be invoked with the exec() function:
var exec = require('exec');
exec('/path/to/your/script',
function (stderr, stdout, errorCode) {
// You get here when the executable completes
}
}
EDIT
With newer node.js versions exec() is deprecated, so it's better to use child_process.execFile():
const execFile = require('child_process').execFile;
const child = execFile('/path/to/your/script', [parameters], (error, stdout, stderr) => {
// You get here when the executable completes
});