I'm using NodeJS, and a Python script.
I need to get results from my python script, for that, I use Python-Shell.
See the documentation at this link :
github.com/extrabacon/python-shell
I can get prints by using pythonShell.on and pythonShell.end.
The problem is that I can't send args with this method
Then I use pythonShell.run!
I can send args but it doesn't return prints while it should ....
Can you help to get my prints ?
You can see my short code below, it's a simple code, just to make it work.
var pythonShell = require('python-shell');
app.post('/index/generator/',urlencodedParser, function (req,res){
var options = {
mode: 'JSON',
pythonOptions: ['-u'],
scriptPath: './generator',
args: ['hello','bye']
};
pythonShell.run('generator.py', options, function (err, results) {
if (err) throw err;
console.log("Message %j ",results);
});
})
Here the python code :
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
print(sys.argv[1]+' '+sys.argv[2])
You can use child_process,
make python file executable
chmod +x generator.py
spawn child process
```
const { spawn } = require('child_process');
const ls = spawn('./generator.py', ['hello', 'world']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
```
then use process.send to communicate with parent process
Related
I am creating a node js script that interacts with both python and electron js to create a GUI. I am currently stuck at an error unfortunately. That error being:
Uncaught Error: spawn python ENOENT
This is on line 167 of events.js, a script that I have not been able to find. I have currently set my PYTHON env variable to C:\Python27\python.exe and my PYTHONPATH to C:\Python27.
Here is the code that is being run when this error occurs.
function getselectors() {
var ps = require("python-shell")
var path = require("path")
var amount = document.getElementById('para').value;
var options = {
scriptPath : path.join (__dirname, '/../engine/'), args : [amount]
}
ps.PythonShell.run ('test.py', options, function (err, results) {
if (err) throw err;
swal (results [0]);
});
}
I need to be able to run '/etc/init.d/mongod status' or 'service mongod status' from wihtin a node js file, in order to store the response in the database.
When I run the above commands in the command line, I get the following response:
● mongod.service - SYSV: Mongo is a scalable, document-oriented database.
Loaded: loaded (/etc/rc.d/init.d/mongod)
Active: active (running) since Thu 2017-02-02 08:07:42 UTC; 3h 27min ago
Docs: man:systemd-sysv-generator(8)
Process: 793 ExecStart=/etc/rc.d/init.d/mongod start (code=exited, status=0/SUCCESS)
Main PID: 1027 (mongod)
CGroup: /system.slice/mongod.service
└─1027 /usr/bin/mongod -f /etc/mongod.conf
However, I want to include this status in an API response that I write. Therefore, when a user request my API, I want it to return the mongoDB status check as seen above.
I have tried the following ways:
router.get('/status', function(req, res) {
var databaseCheck = service mongod status // not sure how to do this
res.json({
mongoResponse: '//to have the above status check response here'
});
});
I am new to all this, so any help would be appreciated. I may understand that my thinking is wrong - do let me know if there is a different way of doing this please
Connect a database and then check connection like db.serverConfig.isConnected(). The below code is a full example.
const app = express();
let dbClient;
let db;
let collection;
MongoClient.connect(configuration.mongoDbUri, { useNewUrlParser: true, poolSize: 30 }, (error, client) => {
if (error) {
console.log("Connection failed for some reason. Err: ", error);
return error;
}
db = client.db("myDB");
dbClient = client;
collection = db.collection('myCollection');
app.locals.mongoDb = db;
});
app.get("/status", (req, res) => {
if (db.serverConfig.isConnected()) {
console.log("db.serverConfig.isConnected :", db.serverConfig.isConnected());
return res.send({ result: true});
}
return res.send({ result: false});
});
app.listen(configuration.app.port, error => {});
You can use nodejs child-process module to run a shell command like you would from a terminal. In a terminal you would "service mongod status", in the nodejs child-process you would do the same by putting that command as an argument to the child-process execute function, like so:
const exec = require('child_process').exec;
exec('service mongod status', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
Try code like this into you app:
db.serverConfig.isConnected();
I tried to run a nodejs script with the built in child_process module and it works fine until i give it options. Specially when i add the env property to the options object.
let exec = require('child_process').exec;
exec('node random.js', { env: {} }, (err) => {
console.log(err);
})
Then i get this error: /bin/sh: 1: node: not found.
I have node installed with nvm, maybe that is the cause, but don't know why.
If you exec a new shell from your script this don't have the same environment of the parent shell (your script).
So you have to provide all the needed environment.
In your case I see 2 way you could do.
First: you create a node command with the full path:
let exec = require('child_process').exec;
let node_cmd = '/path/to/my/node/node';
exec(node_cmd + ' random.js', { env: {} }, (err) => {
console.log(err);
});
So you could use env variables to handle the path, or just change it when you need.
Second, pass the path variable to the command:
let exec = require('child_process').exec;
let env_variables = 'PATH='+process.env.PATH;
let cmd = env_variables + ' node random.js';
exec(cmd, { env: {} }, (err) => {
console.log(err);
});
Another way is using the dotenv package.
I need a complete guide or a good reference material to solve the running module commands within javascript file problem.
Say that I often run:
$ npm run webpack-dev-server --progress --colors -- files
How can I run this within a javascript file and execute with
$ node ./script.js
script.js
var webpackDevServer = require('webpack-dev-server');
// need help here
var result = webpackDevServer.execute({
progress: true,
colors: true,
}, files);
Answer
I do something like this for my Webpack bundles. You can simply use child_process.spawn to execute command-line programs and handle the process in a node script.
Here's an example:
var spawn = require('child_process').spawn
// ...
// Notice how your arguments are in an array of strings
var child = spawn('./node_modules/.bin/webpack-dev-server', [
'--progress',
'--colors',
'<YOUR ENTRY FILE>'
]);
child.stdout.on('data', function (data) {
process.stdout.write(data);
});
child.stderr.on('data', function (data) {
process.stdout.write(data);
});
child.on('exit', function (data) {
process.stdout.write('I\'m done!');
});
You can handle all of the events you like. This is a fairly powerful module that allows you to view the process' PID (child.pid) and even kill the process whenever you choose (child.kill()).
Addendum
A neat trick is to throw everything into a Promise. Here's a simplified example of what my version of script.js would look like:
module.exports = function () {
return new Promise(function (resolve, reject) {
var child = spawn('./node_modules/.bin/webpack', [
'-d'
]);
child.stdout.on('data', function (data) {
process.stdout.write(data);
});
child.on('error', function (data) {
reject('Webpack errored!');
});
child.on('exit', function () {
resolve('Webpack completed successfully');
});
});
}
Using this method, you can include your script.js in other files and make this code synchronous in your build system or whatever. The possibilities are endless!
Edit The child_process.exec also lets you execute command-line programs:
var exec = require('child_process').exec
// ...
var child = exec('webpack-dev-server --progress --colors <YOUR ENTRY FILES>',
function(err, stdout, stderr) {
if (err) throw err;
else console.log(stdout);
});
The accepted answer doesn't work on Windows and doesn't handle exit codes, so here's a fully featured and more concise version.
const spawn = require('child_process').spawn
const path = require('path')
function webpackDevServer() {
return new Promise((resolve, reject) => {
let child = spawn(
path.resolve('./node_modules/.bin/webpack-dev-server'),
[ '--progress', '--colors' ],
{ shell: true, stdio: 'inherit' }
)
child.on('error', reject)
child.on('exit', (code) => code === 0 ? resolve() : reject(code))
})
}
path.resolve() properly formats the path to the script, regardless of the host OS.
The last parameter to spawn() does two things. shell: true uses the shell, which appends .cmd on Windows, if necessary and stdio: 'inherit' passes through stdout and stderr, so you don't have to do it yourself.
Also, the exit code is important, especially when running linters and whatnot, so anything other than 0 gets rejected, just like in shell scripts.
Lastly, the error event occurs when the command fails to execute. When using the shell, the error is unfortunately always empty (undefined).
Do you need it to be webpack-dev-server? There is an equivalent webpack-dev-middleware for running within node/express:
'use strict';
let express = require('express');
let app = new express();
app.use(express.static(`${__dirname}/public`));
let webpackMiddleware = require('webpack-dev-middleware');
let webpack = require('webpack');
let webpackConfig = require('./webpack.config.js');
app.use(webpackMiddleware(webpack(webpackConfig), {}));
app.listen(3000, () => console.log(`Server running on port 3000...`));
https://github.com/webpack/webpack-dev-middleware
I don't know how to execute an exe file in node.js. Here is the code I am using. It is not working and doesn't print anything. Is there any possible way to execute an exe file using the command line?
var fun = function() {
console.log("rrrr");
exec('CALL hai.exe', function(err, data) {
console.log(err)
console.log(data.toString());
});
}
fun();
you can try execFile function of child process modules in node.js
Refer:
http://nodejs.org/api/child_process.html#child_process_child_process_execfile_file_args_options_callback
You code should look something like:
var exec = require('child_process').execFile;
var fun =function(){
console.log("fun() start");
exec('HelloJithin.exe', function(err, data) {
console.log(err)
console.log(data.toString());
});
}
fun();
If the exe that you want to execute is in some other directory, and your exe has some dependencies to the folder it resides then, try setting the cwd parameter in options
var exec = require('child_process').execFile;
/**
* Function to execute exe
* #param {string} fileName The name of the executable file to run.
* #param {string[]} params List of string arguments.
* #param {string} path Current working directory of the child process.
*/
function execute(fileName, params, path) {
let promise = new Promise((resolve, reject) => {
exec(fileName, params, { cwd: path }, (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
return promise;
}
Docs
If you are using Node Js or any front end framework that supports Node JS (React or Vue)
const { execFile } = require('child_process');
const child = execFile('chrome.exe', [], (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});
If the .exe file is located somewhere in the machine, replace chrome.exe with the path to the application you want to execute
e.g "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
const child = execFile('C:\Program Files (x86)\Google\Chrome\Application\chrome.exe', [], (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});
Did you ever think about using Batch file in this process? I mean start a .bat file using node.js which will start an .exe file in the same time?
just using answers in the top i got this:
Creating a .bat file in exe file's directory
Type in bat file
START <full file name like E:\\Your folder\\Your file.exe>
Type in your .js file:
const shell = require('shelljs')
shell.exec('E:\\Your folder\\Your bat file.bat')