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
});
Related
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())
}
)
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)
});
});
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
I am trying to write a test script in node.js for another node.js script that is executed via command line with arguments. When the script is executed in the terminal the arguments are accessible using process.argv[2], process.argv[3], etc. However, those arguments are not present when the script is executed in the test script using child_process.exec().
target.js
var arguments = {
arg1: process.argv[2],
arg2: process.argv[3]
};
console.log(arguments.arg1);
// This outputs '100' when target.js is executed from terminal
test.js
var cp = require('child_process');
cp.exec('node target.js 100 200',
function (err, stdout, stderr) {
if (err) {
console.log(err);
}
console.log(stdout);
// process.argv[2] is undefined when executed as a child process
});
Any suggestions on how to get the same behavior when executing via child_process as I do when I execute it from the terminal?
Your problem is elsewhere. (Caveat: node 0.6.12)
I ran a test using this as a.js:
console.log(JSON.stringify(process.argv));
And using your launcher below:
var cp = require('child_process');
cp.exec('node a.js 100 200',
function (err, stdout, stderr) {
if (err) {
console.log(err);
}
console.log(stdout);
});
I get identical expected output:
joe#toad:~/src$ node a.js 100 200
["node","/home/joe/src/a.js","100","200"]
joe#toad:~/src$ node b.js
["node","/home/joe/src/a.js","100","200"]
I'm doing this tutorial on NodeJS: http://www.nodebeginner.org.
Here is the code I find confusing:
var exec = require("child_process").exec;
function start(response) {
console.log("Request handler 'start' was called.");
var content = "empty";
exec("ls -lah", function(error, stdout, stderr) {
response.writeHead(200, {"Content-type":"text/plain"});
response.write(stdout);
console.log(stdout);
response.end();
});
}
I have a router that passes the http response to a request handler that calls the start function. This is happening without a problem. However, the stdout parameter is not returning anything in the browser or in the console. I understand that ls -lah is supposed to give a list of files in the current directory. I have 5 other files in my directory, but nothing is being returned. Any ideas on what is happening here?