How to kill a Python-Shell module process in Node.js? - javascript

I am currently using the python-shell module in a Node based web interface. The issue I am having is mostly syntactical. The code below shows the generation of a python script.
var PythonShell = require('python-shell');
PythonShell.run('my_script.py' function (err) {
if (err) throw err;
console.log('finished');
}):
This is just an example script from here. How do I relate this to node's
var procc = require('child_process'.spawn('mongod');
procc.kill('SIGINT');
The documentation states that PythonShell instances have the following properties:
childProcess: the process instance created via child_process.spawn
But how do I acutally use this? There seems to be a lack of examples when it comes to this specific module

For example -
var python_process;
router.get('/start_python', function(req, res) {
const {PythonShell} = require("python-shell");
var options = {
pythonPath:'local python path'
}
var pyshell = new PythonShell('general.py');
pyshell.end(function (err) {
if (err) {
console.log(err);
}
});
python_process = pyshell.childProcess;
res.send('Started.');
});
router.get('/stop_python', function(req, res) {
python_process.kill('SIGINT');
res.send('Stopped');
});

Related

Attempting to convert an XSD to JSON

I am attempting to convert an XSD to JSON using the XSD2JSON2 package. I have tried the below, but the users.json file is not created
var xsd2json = require('xsd2json2').xsd2json;
var fs = require('fs');
xsd2json('users.xsd', (err, jsonSchema) => {
fs.writeFile('users.json', jsonSchema, (err) => {
if (err) throw err;
console.log('JSON schema created')
});
});
I tried the above after getting a 'callback not defined' issue with XSD2JSON2's usage code:
var xsd2json = require('xsd2json2').xsd2json;
var fs = require('fs');
xsd2json('./users.xsd', function(err, jsonSchema) {
fs.writeFile('./users.json', jsonSchema, callback);
});
I am currently learning JS (as you can probably tell) so any assistance would be appreciated.

Node.js: Execute server scripts via front-end

I'd like to execute some specific node JS files with an on-click event at my Website.
I'm using express to run my server and website. I think the right way to do this is using jQuery with some GET requests. The JS files are working, if i call them simply in the console with "node examplefile.js"
The file looks like this:
var MapboxClient = require('mapbox');
var client = new MapboxClient('');
client.listStyles(function (err, styles) {
console.log(styles);
});
I want to execute this file everytime an on-click event occurs.
Do I have to export this as a module to my app.js? This is what I wanted to do, but I failed in the implementation.
Any suggestions or simple examples on how to realize this?
1.Write your examplefile.js within a function
function a(){
var MapboxClient = require('mapbox');
var client = new MapboxClient('');
client.listStyles(function (err, styles) {
console.log(styles);
});
2.Include examplefile.js in your app.js
<script src="examplefile.js" type="text/javascript"></script>
3.Then call a() by onclick() event from your app.js file
<input type="button" onclick="javascript: a();" value="button"/>
That is what i understood, you are trying to do.
It's much better to create a new module and then call it from express app
create new module (getStyles.js):
var MapboxClient = require('mapbox');
var client = new MapboxClient('');
module.exports = function (done) {
client.listStyles(function (err, styles) {
if (err) {
return done(err);
}
done(null, styles);
});
}
Use it inside express app:
...
var getStyles = new MapboxClient('path/to/getStyles');
app.get( '/your/route/here', function (req, res, next) {
getStyles( function (err, styles) {
if (err) return next(err);
res.render('view', styles)
});
});
...
However if you want to execute a command line from express, then use exec function, here is an example:
...
const exec = require('child_process').exec;
app.get( '/on/click/buton/route', function (req, res, next) {
exec('/usr/bin/node file/path/.js', function (err, stdout, stderr) {
if (err) {
return next(err);
}
// send result to the view
res.render('veiw', { res: stdout});
});
});
...

how to run different .js file in one server.js file in NODE JS?

this is demo.js file and i want to use this file in server.js file so that i can use diffrent js files in one server file.
Demo.js:
app.get('/add User', function (req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/project';
MongoClient.connect(url, function (err, db) {
var collection = db.collection('users');
collection.find({name: 'shruti'}).toArray(function (err, result) {
console.log(, result);
db.close();
});
Server.js:
var a = require('./demo.js');
vr http=require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write(a);
res.end();});
server.listen(7860);
A possible sample would look like :
demo.js
var myModule = {
defineRoutes: function(router){
//do something...
}
}
module.exports = myModule;
server.js
var myModule = require('demo.js');
myModule.defineRoutes(router);
As stated, you need to export.
When you do:
var item = require("mymodule");
Require returns an object, which is a reference the value of module.exports for that given file - in your case demo.js.
You can write your modules a few ways as some people have shown you. Because it is encapsulated you basically are identifying what is public or can be called. Few ways to write it - you could also do:
module.exports = {
yourCall: function () {
console.log("stuff here");
}
};
As stated by #ishann, who is dead on here, you are writing something you assume might be populated. Going to a database and returning is an asynchronous call - so it will take time to go do that and then for the results to be returned.
Based on your structure - ideally what you want to do is assign the route ( "/addUser" ) which will pass in the response object to you:
app.get('/add User', function (req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/project';
MongoClient.connect(url, function (err, db) {
var collection = db.collection('users');
collection.find({name: 'shruti'}).toArray(function (err, result) {
console.log(, result);
db.close();
// set the type
res.writeHead(200, {"Content-Type": "application/json"});
res.write(result);
});
Just looks like your code needs a bit of reorg, but separting concerns is good. You might want to also check out Express as a framework for node.

LoopBack: cannot call method 'post' of undefined

I am new to loopback and node.js.
I have created two models: Rating and RatingsAggregate
using the loopback explorer, I can query and post against the API just fine.
I am try to setup some basic business logic so I am editing the file Rating.js in common/models
Here is the content of it:
module.exports = function(Rating) {
Rating.afterRemote('**', function(ctx, inst, next) {
var loopback = require('loopback');
var app = loopback();
var ratingsaggregate = app.models.ratingsaggregate;
ratingsaggregate.post({"source":"foobar","restaurantID":"foobar","itemMenuName":"foobar","itemSectionName":"foobar","itemName":"foobar","nRatings1":123,"nRatings2":123,"nRatings3":123,"nRatings4":123,"nRatings5":123,"hasImage":true,"imageSize":123,"latestImageRatingID":"foobar","imageCount":123,"lastUpdated":"foobar"}, function(err, response) {
if (err) console.error(err);
next();
});
});
};
I can load my API, but whenever I run a get statement against it, I get this error:
TypeError: Cannot call method 'post' of undefined
My guess is that somehow ratingsaggregate never gets a value... but I don't know what I am doing wrong. Obviously this is not the end state of my business logic, but I am trying some basic CRUD right now between two models
And... here is the answer. There was a getModel function hidden in the documentation
module.exports = function(Rating) {
Rating.afterRemote('create', function(ctx, inst, next) {
var loopback = require('loopback');
var ratingsaggregate = loopback.getModel('ratingsaggregate');
ratingsaggregate.create({"source":"foobar","restaurantID":"foobar","itemMenuName":"foobar","itemSectionName":"foobar","itemName":"foobar","nRatings1":123,"nRatings2":123,"nRatings3":123,"nRatings4":123,"nRatings5":123,"hasImage":true,"imageSize":123,"latestImageRatingID":"foobar","imageCount":123,"lastUpdated":"foobar"}, function(err, response) {
if (err) console.error(err);
next();
});
});
};
Fixes everything and the behaviour is the expected one

How to use node-mysql correctly with Express.js?

I'm wondering how to use the module node-mysql correctly in Node.js (using Express.js). I have a main router with this:
var Post = require('./models/post.js');
app.get('/archives', function (req, res) {
Post.findArchives(function(posts, err) {
if(err)
res.send('404 Not found', 404);
else
res.render('archives', { posts: posts});
});
});
And here's the content of the file post.js:
var mysql = require('mysql');
var dbURL = 'mysql://root#localhost/mydatabase';
exports.findArchives = function(callback) {
var connection = mysql.createConnection(dbURL);
connection.query('SELECT * FROM blog_posts_view WHERE status != 0 ORDER BY date DESC', function(err, rows) {
if(err) throw err
callback(rows, err);
connection.end();
});
};
How can I improve it? Improve the error handling? Also, there's the function handleDisconnect(connection); on their Github (https://github.com/felixge/node-mysql) that I'm not really sure how to integrate to make sure that the application will not crash when the database is not responding.
Thanks!
Take a look at the mysql-simple library. It combines node-mysql with a pooling library to create a connection pool, and also includes the code to handle the disconnects.
If you want to make it super easy, you could just use that module.

Categories