Forever module with node app executable file - node.js

I am working on Node JS application.
In this I have to check first user is connected with internet or not. If yes then check KinectRuntime-v2.0_1409-Setup installed or not.. and further more such kind of validations are there. so I have used the following code in my entry script:
What I have Done:
broadcast.js: // entry file which we use to start app
var tempkinect = require('./controllers/tempkinect.js');
tempkinect.controller(app);
require('dns').lookup('google.com',function(err) {
if (err){
server.listen(8000, function(req, res){
open('http://localhost:8000/internetnotfound'); // internet not found page.
return false;
});
}
else{
try{
var Kinect2 = require("kinect2");
var kinect = new Kinect2();
}
catch(ex) {
server.listen(8000, function(req, res){
open('http://localhost:8000/kinectnotfound');
open('https://www.microsoft.com/en-in/download/confirmation.aspx?id=44559');
return false;
}
} //else ends here
});
tempkinect.js file: // my controller file
module.exports.controller = function(app){
app.get('/kinectnotfound',function(req,res){
var errmsg = "KinectRuntime-v2.0_1409-Setup not installed on your computer. Download will start automatically, if not then";
var link = "https://www.microsoft.com/en-in/download/confirmation.aspx?id=44559";
var click = "Click Here!"
res.render('initialerror',{errormessage:errmsg, downloadlink : link, clickhere: click, title : 'Kinect Not Found'});
});
app.get('/internetnotfound', function(req,res){
require('dns').lookup('google.com',function(err) {
if (err){
res.render('initialerror',{errormessage:'Please Connect Internet for Login.',downloadlink : '', clickhere : '', title : 'Internet Not Connected'});
}
else{
res.redirect('/restart');
}
});
});
app.get('/restart', function (req, res, next) {
process.exit(1);
});
}
I am using enclose module which compiled the node js application and creates .exe file. Now, If I run application on my local machine using command prompt:
run > node broadcast.js
then in case of internet not found app displays corresponding page.( then I connect internet manually ) after connecting internet when I refresh the page it restarts the process, which is good as per required.
BUT, when I do the same using compiled application then it is giving me error:
What Error I am getting:
So can anyone please suggest what should be modified there?
Besides this, Forever should be installed as global on the system so it is working fine on my system but not on others with the compiled app.

Looks like you already have something running at port 8000 (possibly other copy of your app). I would make sure your app port is configurable either through environment variables or command line options. Likewise make sure it can be shut down gracefully to release the port.
As for forever, there is no reason to install it globally, package it with the application and then its available at ./node_modules/.bin

Related

Issues Getting Highcharts Export Server Running Under iisnode

I am working on trying to set up the Highcharts export server under node.js using iisnode (https://github.com/tjanczuk/iisnode). It basically acts as a pipe between requests to IIS through to node. Great! Only, how do I "install" the highcharts export server so it is using iisnode? I did the instructions on how to install the highcharts-export node module but it is installed under (Windows) AppData\Roaming\npm. How to move or point iisnode to the export server?
This export server is run via the following once installed from npm:
highcharts-export-server --enableServer 1
So, to get this installed and used in IIS8 + iisnode
1) What is the right directory to install export server locally (on Windows the modules pulled in via npm go to C:\Users\\AppData\Roaming\nmp\ where is the logged in user using npm to install the package)?
2) What is the iisnode configuration necessary for this?
I have the iisnode setup and running on our development box and all the examples work. My confusion lies partly with the utter lack of documentation for issnode. All the links I have found just repeat the items listed in the links from the issnode developer with no actual "here is how you take a node app that exists in npm and have it work in issnode." I don't necessarily need my hand held every step of the way. I am just seeing no list of steps to even follow.
install node (if not already installed)
install iisnode (if not already installed => https://github.com/tjanczuk/iisnode)
verify IIS has iisnode registered as a module
create a new Application Pool, set to "No Managed Code"
create a new empty web site
load the iisnode sample content into it, update the web.config
verify you can hit it and it runs and can write it's logs
go to the IIS web site folder and run these npm commands
npm init /empty
npm install --save highcharts-export-server
npm install --save tmp
add file hcexport.js and reconfigure web.config
var fs = require('fs');
var http = require('http');
var path = require("path");
var tmp = require('tmp');
const exporter = require('highcharts-export-server');
http.createServer(function (req, res) {
try {
if (req.method !== 'POST') { throw "POST Only"; }
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
if (body === '') { throw "Empty body"; }
var tempFile = tmp.fileSync({discardDescriptor: true, postfix: ".svg", dir: process.cwd()});
var input = JSON.parse(body);
input.outfile = path.basename(tempFile.name);
exporter.initPool();
exporter.export(input, function (err, exres) {
if (err) { throw "Export failed"; }
var filename = path.join(process.cwd(), exres.filename);
exporter.killPool();
fs.readFile(filename, function(err, file) {
res.writeHead(200, { 'Content-Type': 'image/svg+xml', 'Content-disposition': 'attachment; filename=' + exres.filename });
res.write(file.toString());
res.end();
tempFile.removeCallback();
});
});
});
} catch (err) {
console.log({port: process.env.PORT, error: err});
res.writeHead(409, { 'Content-Type': 'text/html' });
res.end(err.message);
}
}).listen(process.env.PORT);
Extend as needed to support the export types you plan to use.
The highcharts-export-server uses phantomjs internally and this can run away under some error conditions using up 100% of available CPU, if you see this you can kill it using:
Taskkill /IM phantomjs.exe /F
The solution from saukender seems to work, however it seems that it always initializes a new pool of phantom workers every time.
If you already have node and issnode setup, another solution is to directly start the highcharts export server and not call the export function manually. This seems to provide a better performance, since it doesn't initialze the worker pool on every request.
// app.js
const highcharts = require("highcharts-export-server");
highcharts.initPool();
highcharts.startServer(process.env.PORT || 8012);
Don't forget to point your web.config to app.js.
I found these two resource quite useful during setup:
https://www.galaco.me/node-js-on-windows-server-2012/
https://tomasz.janczuk.org/2011/08/hosting-nodejs-applications-in-iis-on.html

Using directory (for images links etc) in Openshift (nodejs application)

I have a webpage that I have hosted using a node application on openshift. Its here
http://nodejs-volition.rhcloud.com/
My question is very simple (although I haven't found anyone else asking it). How do I refer to other files in the directory which contains index.html
For instance I would like to use an image that is in the directory in the index. My current html for the image is
<img src="$OPENSHIFT_REPO_DIR/images/1416870991752.jpg" alt="spark core">
I have also tried using "images/1416870991752.jpg". I have the same problem with linking to other html files in the directory?
What am I doing wrong? Please help?
As corey112358 alludes to below the key is in that to host using nodejs a server must be defined. My application already has a server file, so rather than creating a new server I must modify the existing one. I've done it successfully now, there were two changes to make to the server.js file.
The 1st change is modification of the cache. That should look like this...
self.zcache['index.html'] = fs.readFileSync('./index.html');
self.zcache['page2.html'] = fs.readFileSync('./page2.html');
self.zcache['sparkcoredark.jpg'] = fs.readFileSync('./sparkcoredark.jpg');
The first line was already included but the next two were added by me to include another html page and an image.
The second step is modify the self.createRoutes section of the server.js file as below (asciimo image is included by default).
self.createRoutes = function() {
self.routes = { };
self.routes['/asciimo'] = function(req, res) {
var link = "http://i.imgur.com/kmbjB.png";
res.send("<html><body><img src='" + link + "'></body></html>");
};
self.routes['/'] = function(req, res) {
res.setHeader('Content-Type', 'text/html');
res.send(self.cache_get('index.html') );
};
self.routes['/page2.html'] = function(req, res) {
res.setHeader('Content-Type', 'text/html');
res.send(self.cache_get('page2.html') );
};
self.routes['/sparkcoredark.jpg'] = function(req, res) {
res.setHeader('Content-Type', 'image/jpg');
res.send(self.cache_get('sparkcoredark.jpg') );
};
};
Hope that helps out anyone else struggling with this issue. Thanks to coreyfibonacci

Deploying Node/Mongo to Openshift

Hello I'm trying to get Node/Mongo service going on Openshift, here's what it looks like:
var db = new mongodb.Db('myServiceName',
new mongodb.Server('mongodb://$OPENSHIFT_MONGODB_DB_HOST','$OPENSHIFT_MONGODB_DB_PORT', {}));
db.open(function (err, db_p) {
if (err) { throw err; }
db.authenticate('$USER', '$PASS', function (err, replies) {
if (err) { throw err; }
// should be connected and authenticated.
// ...
The app was created using rhc:
$ rhc create-app myServiceName nodejs-0.10 mongodb-2.4
The console shows the app was started and is running, and on cURL the response is 503
My logs don't show an error, however, the dB is obviously not live. Can anyone help?
If your mongodb driver supports connection with username/password, then use OPENSHIFT_MONGODB_DB_URL instead of OPENSHIFT_MONGODB_DB_HOST
OPENSHIFT_MONGODB_DB_URL gives you this format:
mongodb://admin:password#127.4.99.1:27017/
and OPENSHIFT_MONGODB_DB_HOST gives you this format:
ip addres, ex: 127.4.99.1
So you can just use OPENSHIFT_MONGODB_DB_URL to connect and authenticate at the same time
with mongoskin, you can just do this:
var db = require('mongoskin').db(process.env.OPENSHIFT_MONGODB_DB_URL + 'dbname'+ '?auto_reconnect=true',
{safe: true, strict: false}
);
It looks like you are attempting to connect to a server named "$OPENSHIFT_MONGODB_DB_HOST", (not a valid URL).
Instead, you'll probably want to read the value of the OPENSHIFT_MONGODB_DB_HOST environment variable to find your connection information:
process.env.OPENSHIFT_MONGODB_DB_HOST
I have some additional notes up here: https://www.openshift.com/blogs/getting-started-with-mongodb-on-nodejs-on-openshift

how to get id from url in express, param and query doesnt seem to work

I have a url, i'm trying to get id but none of it is working req.params nor req.query
app.get('/test/:uid', function testfn(req, res, next) {
debug('uid', req.params.uid); // gives :uid
debug('uid', req.query.uid); // gives undefined
});
I'm doing an ajax call like this
$(document).on('click', 'a.testlink', function(e) {
$.ajax({
type: "GET",
url: '/test/:uid',
success: function(var) {
console.log('success');
},
error: function() {
alert('Error occured');
}
});
return false;
});
I'm using
app.use(express.json());
app.use(express.urlencoded());
instead of body parser
Your code is working as expected: The ajax call specifies url: '/test/:uid' which is what puts :uid in req.params.uid.
Try sending something else: url: '/test/123' and req.params.uid will contain 123
Here is an example that will work. I will give step by step instructions from the start:
express myproject
cd myproject
npm install
Open app.js and add in the following somewhere in the file - maybe right before the line app.get('/test/:uid',test);
var test = function(req,res,next) {
// do whatever logic is needed
res.end('Displaying information for uid ' + req.params.uid);
}
app.get('/test/:uid',test);
Now, open up a new terminal, make sure you are in the myproject directory and enter:
node app.js
Now you can visit http://localhost:3000/test/45 on the local machine and you should see:
Displaying information for uid 45
If you are not accessing from your local machine make sure to change the url above to match whatever server your node app is running on.
Also, this is just a simple example. You might be better off organizing everything by placing the routes in files similar to the routes directory example setup in a new install of an express app. You can find more detailed examples of this on the web like this one and this one. Also, one of the best explanations of organizing/reusing code in Node this I have seen is in the book NodeJS in Action.

Access SFTP from NodeJS

I have a need where i have to open a SFTP connection with a server, copy a file from there to local.
To that end, i have tried installing node-sftp module using
npm install node-sftp
It didnt work out of the box, i had to replace the sftp.js file that was installed by npm with that of github repository here : https://github.com/ajaxorg/node-sftp
(npm version was using TTY and github version was using PTY. i am not sure what they are)
After start the server and invoking the code, i see this in console.
launching: sftp -o Port=22 jash#xxx.63.xxx.49
listening...
console just hangs here. I am trying to print all files in the current directory after connection is opened.
This is the code
var http = require('http');
var Sftp = require('node-sftp');
var port = process.env.PORT || 1337;
var msgHandler = function(request, response) {
var options = {
host:"xxx.63.xxx.49",
username:"jash",
password:"mypassword",
port:22
};
var conn = new Sftp(options,function(err){
console.log(err);
});
conn.cd(".", function(err) {
console.log(err);
conn.ls(".", function(err, res) {
console.log(res[0].path);
});
});
console.log("listening...");
}
http.createServer(msgHandler).listen(port);
The credentials are fine, i used them in SecureCRT and was able to login.
The second argument to Sftp() (the function(err)...) is where you want to place your conn.cd(... code. It (said 2nd argument) is a function that gets called once the connection has been established. Make sure to check for err of course.

Resources