Im working on couple of sites, both have 2 versions, live one and dev one.
http://timeprize.com and http://test.timeprize.com
They both run on the same port and server, using express vhost.
My vhost app looks very simple, and is basically this:
var evh = require('express-vhost'),
express = require('express');
/*... some more variable declarations ...*/
if ( site_enabled('test.timeprize.com') ) {
/**/
evh.register('test.timeprize.com', function() {
var app = express();
app = require("../test_app/app.js").run_app(http);
return app;
}() );
};
if ( site_enabled('timeprize.com') ) {
evh.register('timeprize.com', function() {
var app = express();
app = require("../live_app/app.js").run_app(http);
return app;
}() );
};
/*... more sites below ...*/
Im running the code above using "forever" process.
And now the problem.
Since the test site, and live site are both running on the same server/port using same process, how do i update/restart the test site, without interrupting the live site ?
To address the:
Since the test site, and live site are both running on the same server/port using same process
This shouldn't occur. Your server should throw an error when a second program attempts to listen to a port already occupied.
To answer the real question:
How do I update/restart the test site, without interrupting the live site?
The answer is don't use forever. Yes, it's easy and whatever but for servers with multiple applications running in sync, the must use program is PM2
Install globally:
[sudo] npm i -g pm2
Start your apps, sudo if it listens to a port below 1024:
[sudo] pm2 start app.js
Restart your apps with:
[sudo] pm2 restart [all|name]
OR
[sudo] pm2 gracefulReload [all|name]
Check out documentation
Related
I've read other forums on installing express, I have run
npm install express -g on command prompt as admin.
I did this command a few times and restarted my computer multiple times but Express is still not recognized.
Any help is appreciated.
Express isn't a web server; it is a framework for building web servers.
The express package doesn't provide anything directly executable.
The express documentation has a getting started guide.
If you aren't trying to do server-side programming using Node.js and just want an HTTP server, then the http-server package may be more your speed.
Assuming you’ve already installed Node.js, create a directory to hold your application and make that your working directory.
then follow the below command
npm init
follow step press enter and after
npm install express
make index.js file paste below hello work program.
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Now you can run file using below command
node index.js
Open your broswer and enter URL : http://localhost:3000/
You can display Hello World!
You have successfully installed node js and express js program.
I created a frontend app and now trying to incorporate backend into it.
ON the same frontend app i added an index.js file in the root directory, and installed express and required it in index.js file.
Very basic setup as below:
const express = require('express')
const cors = require('cors')
const port = process.env.PORT || 3001
const app = express()
app.get('/', (req, res) => {
res.send({
greetings: 'hi'
})
})
app.listen(port, () => {console.log(`Server on port ${port}`)})
Server is successfully on port 3001 as per my terminal, however, on localhost:3001 I'm not seeing any json response I set up in app.get.
It says Cannot GET / instead. When i inspected in devtool(Network) it says 404.
This seems a very straightforward setup, but what could've gone wrong here?
i just figured why. I installed nodemon but my “start” script is “node index.js”. Should’ve used “nodemon index.js”
Working now with nodemon index.ks
Your code is fine, There are no errors, I tested it and it works as expected.
However few things to note, Keep Backend in Seperate folder/dirctory unless required.
Coming back to your question, There are many possiblity such as some modules are not installed properly
try running following command
//this will install if any library is currupt or not installed properly
npm i
if it doesn't work then try clearing cache
Also keep in mind, In nodeJS dev server does not automatically refresh changes, you need to restart server to see changes or you can use dev dependancy called Nodemon (this will auto restart server on saving changes)
I am using Node/Express.js server on Windows Server 2012 R2 in the production and PM2.js to keep applications alive forever and to reload them without downtime. Since PM2 has limitations on Windows OS, I have chosen PM2-installer software to overcome them.
The server runs fine when I run with Node, so there is no issue with the server script.
node index.js
But, when I start the server with PM2, the server doesn't start and the status is "errored" (I had tried ecosystem file and cluster mode as well earlier with no luck).
pm2 start index.js
The logfile is empty, so there is no clue. Has anybody encountered this? Any solution?
Update 1:
I noticed the following error in service.log in C:\ProgramData\pm2\service
2021-03-23T23:13:56: PM2 log: App [server-plugin:0] starting in -fork mode-
2021-03-23T23:13:56: PM2 log: App [server-plugin:0] online
ERROR: 2021-03-23T23:13:56: PM2 error: Error: spawn node ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:269:19)
at onErrorNT (internal/child_process.js:465:16)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
3/23/2021, 11:13:56 PM: default/server-plugin#N/A - start - MANUAL
ERROR: 2021-03-23T23:13:56: PM2 error: Cancelling versioning data parsing
The error seems to indicate that it is not able to spawn node.js, but not sure why.
Update 2:
index.js is small test App directly in root folder and contains just this:
const fs = require('fs');
const express = require('express'),
https = require('https'),
const config = require('./config');
const hostname = config.hostname;
const port = config.port;
const app = express();
app.get("/*",(req, res, next) => {
console.log(req.headers);
res.send(`<html><body><h1>Hello ${req.params[0] || 'World'} from ${port} port!</h1></body></html>`);
});
https.createServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
}, app).listen(port, hostname, () => {
console.log(`Server running at https://${hostname}:${port}`);
There is an accompanying config.js, the SSL files and node_modules sub-folder in the root folder. That's all.
The solution for me was to abandon pm2-installer and use a Task scheduler approach. This solution was the savior. It works like a charm. An additional tip is to set the environment variable PM2_HOME to c:\users\<user>\.pm2 or something like that. This will help PM2 resurrect to pick up the dump file from this location. Also restart the machine for this scheme to work but if it is not possible to restart, run the created scheduled task manually.
I am new to node.js and I want to get webserver running but I got this problem where trying to debug application by running node ./bin/www works perfectly but trying to launch it by node app.js dosen't do anything.
When i type out node app.js in terminal blank line appears like its loading something and dissapears in few seccods without any error or starting application.
The problem is that app.js is exporting an app object, not starting a server. If you look at the code for bin/www you'll see that it loads the app object and uses it to start a server.
#!/usr/bin/env node
var debug = require('debug')('tmp');
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
You need to either start the app using bin/www, or modify and move that code to the end of app.js if you don't want the separate start script.
If you want to see the debug messages, you need to add the DEBUG environment variable to your shell session. For development environments, you could do this automatically by placing it in your .bashrc file.
export DEBUG=express:*
Or if you do not want to do that, you can just do this:
DEBUG=express:* node ./bin/www
http://expressjs.com/guide.html#debugging-express
I'm trying to get my first production node website up (just a basic hello world on my production web server).
The below is what I'm using (basic http proxy to pass off apache websites to port :9000 and node websites to port :8000). I know this part works because apache vhosts are forwarded as I expect. What does not work however is the node part -instead I get the error below
"Cannot GET /"
This is running node 0.8.1 on Ubuntu 12.04
I'm hosting this with forever.js (forever start foo.js). when I echo the NODE_ENV -it shows "production"
It might also be noted that I don't have node_modules on the path (as you will see in my require statements) **not sure if this has anything to do with my issue
var httpProxy = require('/usr/local/lib/node_modules/http-proxy/lib/node-http-proxy');
var express = require('/usr/local/lib/node_modules/express/lib/express');
httpProxy.createServer(function (req, res, proxy) {
var nodeVhosts = ['www.mysite.com'];
var host = req.headers['host'];
var port = nodeVhosts.indexOf(host) > -1
? 8000
: 9000;
proxy.proxyRequest(req, res, {host: 'localhost', port: port});
}).listen(80);
var one = express.createServer();
one.get('/', function(req, res){
res.send('Hello from app one!')
});
var app = express.createServer();
app.use(express.vhost('localhost', one));
app.listen(8000);
Since you are running Ubuntu, you might take a look at upstart. In case you don't know, upstart replaces the old-school-unix init-scripts approach to starting and stopping services. (Those were dark, scary days!) If you want your app to start automatically when your box boots/reboots and restart automatically after it (your app) crashes, then you want upstart. Learning the basics of upstart is easy, and then you have a tool that you can use over and over again, whether it's node, apache, nginx, postfix, mongodb, mysql, whatever!
I mean no disrespect to the good folks who work on the forever module. Arguably, it does have a solid use case, but too often it is used to imperfectly duplicate the bedrock which is already on your system -- upstart. Also, you might Google for some of the comments made by experienced users and some node.js committers about the forkability of node.js and the pitfalls, which are very relevant to forever.
I'd like to post links, but I don't have enough rep yet. Hopefully what I wrote is enough to google on.
Good luck!
http-proxy module doesn't change the host header of the request, and that's what connect/express vhost uses to distinguish virtualhosts.
In this line:
proxy.proxyRequest(req, res, {host: 'localhost', port: port});
you tell the proxy server to proxy the unchanged request to localhost:port.
So what you need to do is to change:
var app = express.createServer();
app.use(express.vhost('localhost', one));
app.listen(8000);
to:
var app = express.createServer();
app.use(express.vhost('www.mysite.com', one));
app.listen(8000);
and it should work.
Alternatively you can simply set the req.headers.host to localhost before proxying.