I'm using the cluster module to fork my application in my index.js (which is the main file in my application/root directory of my website). Now my app contains many routes. Should I include the cluster code to wrap all my route files?
For e.g.
Consider my index.js file
var cluster = require('cluster');
if(cluster.isMaster)
{
cluster.fork();
cluster.fork();
cluster.on('disconnect', function(worker)
{
console.error('disconnect!');
cluster.fork();
});
}
else
{
var express = require('express');
var app = express();
app.get('/',function(req,res){
//application logic goes here
});
var route1 = require('./route1.js');
app.route('/route1',route1);
app.listen(80);
}
So ,in my route1.js file, should I wrap it around the cluster-code just as I did around my index.js file or it's not necessary?
Your clusters are the ones who are receiving the http request in the end. They have to know what code, each cluster has to run based on the route. The way you have done it is already correct. If you are taking your project on production you might consider using a process manager like PM2
Related
Im am trying to load images in phaser with node js and i always get the same error
:3000/assets/img/feet/idle/survivor-idle_0.png:1 Failed to load resource: the server responded with a status of 404 (Not Found)
if you know a way to get this to work please tell me. here is my code:
preload() {
// Used for preloading assets into your scene
//Idle feet image
this.load.image('idleFeetFrame', '/assets/img/feet/idle/survivor-idle_0.png');
}
(Updated from Comment)
... is my server code:
const express = require('express');
const app = express();
const server = app.listen(process.env.PORT || 3000);
app.use(express.static('./public'));
console.clear();
console.log('\x1b[36m%s\x1b[0m', 'Server started...\n');
const socket = require('socket.io');
const io = socket(server);
io.sockets.on('connection', handleConnection);
function handleConnection(socket) { console.log('Client: ' + socket.id + ' has connected.') }
Since there are not any special routes configured in express, I assume all your files are in the folder ./public.
In that case the file survivor-idle_0.png would have to be in the folder ./public/assets/img/feet/idle/survivor-idle_0.png if you can't find it in that path, that is the problem (check for typos, or extra folder like src).
As long as you are not using a bundler like webpack, parcel or so, just need to check your the public folder and fix the paths.
If you are using a bundler, you will have to check the bundler configuration for errors.
I have an Express app whose server.js file has maybe 30 GET and POST endpoints, like this:
const express = require('express');
const app = express();
const http_port = 8000;
app.listen(http_port,()=>{
console.log(`app listening on port ${http_port}`);
});
app.get('/create_something',function(req,res){
createSomething();
res.send('create');
});
app.post('/update_something',function(req,res){
updateSomething();
res.send('update');
});
//and so on for 30 more endpoints
For ease of maintenance, I want to break this set of endpoints up into different files, e.g. video.js and audio.js.
Thinking this solution might help, I created another file other_route.js:
var express=require('express');
var router=express.Router();
router.get('/other_route_endpoint',function(req,res){
res.send('other_route_endpoint');
});
module.exports.router=router;
and then including this in server.js by changing my initial declarations to:
const express = require('express');
const app = express();
const http_port = 8000;
var router=express.Router();
router.use('/other_route',require('./other_route').router);
But when I visit myserver.com:8000/other_route_endpoint, I get this error:
Cannot GET /other_route_endpoint
How can I add in endpoints from other files into server.js, so I can move some of its many endpoints into these subfiles?
First, your main file should not be using a router. Change the line to app.use('/other_route',require('./other_route').router);.
Second: each path you set with router.use in the routing file will be relative to the path specified in app.use. See https://expressjs.com/en/guide/routing.html#express-router
For example, if you have this in your main file
app.use('/foo', require('./bar.js'));
And this in bar.js
router.get('/bar', /* do something */);
Then the corresponding endpoint would be /foo/bar.
I have two angular projects and I want to serve them on the same domain like for example if I do mywebsite.com/app1 get the first project and when I do mywebsite.com/app2 get the second project.
If you need them to run on the same node server then just create controller routes for each to separate them. If you mean that you both need them to run on the same physical server then you can look into sub domains and have app1.mywebsite.com point to one running node server and app2.mywebsite.com point to another. This would allow them to be split between 2 node processes.
Simply make 2 folders inside dist for each app and serve the static files using express.static
var express = require('express');
var path = require('path');
var app = express();
app.use('/app1', express.static(path.normalize(__dirname + './../dist/app1')));
app.use('/app2', express.static(path.normalize(__dirname + './../dist/app2')));
create two folder on your node app
app1
app2
put the result of ng build of both project in those folders by editing your angular.json file and specify the outDirand the same for the scond app 'app2' :
"outDir": "/path/to/your/node/app/app2"
"outDir": "/path/to/your/node/app/app1"
then in your node app just tell the app which folder to serve from on the specific route :
app.use('/app1', express.static('app1'));
app.use('/app2', express.static('app2'));
app.use('/', express.static('index.html'));
I have this code now, it is serving the correct app but in Angular it isn't finding the correct js files it's looking in the root directory like localhost:8080/main.js instead it must look at localhost:8080/app1/main.js
const express = require('express');
const app = express();
const path = require('path');
app.use('/app1', express.static(path.normalize(__dirname + '/app/app1')));
app.use('/app2', express.static(path.normalize(__dirname + '/app/app2')));
app.listen(8080, () => {
console.log('Server is litening on port 8080');
});
Folder structure
bin - www.js
lib - jsFiles...
models - jsFiles...
node_modules -Folders and Files
public - index.html
route - jsFiles...
index.js
package.json
I use Express, angular.js. Server starts at www.js and It calls
index.js. After that, When I type merely "localhost:3000" It shows me
public/index.html. I don't have route for '/' but It shows me
'public/index.html'. I can not understand this. Please let me know
about the process.
www.js
var debug = require('debug')('example-server');
var app = require(process.cwd()+'/index');
//listen at 3000 port
app.set('port',process.env.PORT || 3000);
var server = app.listen(app.get('port'),function()
{
debug('Express server listening on port ' + server.address().port);
});
index.js
var favicon = require('serve-favicon');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//Connection for DB
require('./lib/connection');
var employees = require('./routes/employees');
var teams = require('./routes/teams');
var app = express();
// Writing at routing table
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname,'public')));
app.use(employees);
app.use(teams);
// send 404 to errorhandler
app.use(function(err,req,res,next)
{
var err = new Error('Not Found');
err.status = 404;
console.log(error);
next(error);
});
...
...
module.exports = app;
In express.js the sequence in which you register your middleware makes a huge difference.
When express.js receives a request, it starts from top and executes registered middleware.
Middlewares are registered in express app using app.use(middleware_goes_here) this type of middleware gets executed no matter what the request url is on the other hand you can also register a middleware like app.use('/url/path',middleware_goes_here) in this case we are registering this middleware to '/url/path' so this middleware will only get executed when you visit '/url/path' (and non of the previous matching middleware serves the request without calling next() )
This app.use(express.static(path.join(__dirname,'public'))); line of code does the magic.
You can go here (express.static ref) to know more about static content serving and routing.
Basically what happens is, we are configuring express.static middleware to serve static content "as is" from "public" folder. So when you make any request and it matches a static content in public folder, then it will serve it otherwise express.static will call next middleware in sequence.
So in your case, the first middleware that actually server input request is express.static without any route filters, so it servers index.html even without a specifically defined route. If your public folder had file at public/javascript/jquery.js then following url will map to it http://localhost:3000/javascript/jquery.js
NOTE: You do not have to specify "public" in the url, the way in which express.static is registered, it will server contents FROM "public" folder.
................
UPDATE: How does default work in express.static?
By default, app.use(express.static(path.join(__dirname,'public'))); this will take index.html as default document. If you want to set index2.html as your default document, you can do that by doing something like this app.use(express.static(path.join(__dirname,'public'),{index: 'index2.html'}));
Hope it helps.
Put a relative path to folder(one up in hierarchy).
var app = require('../index');
I am new to NodeJS. What I wanted to know is, can I like call 2 JS files using NodeJS & ExpressJS. Basically I want to have 2 seperate files so I can work on one and my partner can work on another one. So I want Server.js to call one file which contains some part of my REST API and other one contains rest of the function.
|--NodeModules[etc..]
|--Server.js
|--Rest/
| |--RestAPI1.js
| |--RestAPI2.js
It will be really helpful in the development of my project, if this is possible.
You can define routes in different files like this:
Server.js
var express = require('express')
var router1 = require("./routers/router1");
var app = express();
.....
app.use("/user", router1);
Router1.js
var router = require("express").Router();
router.get("/", function(req, res) {
...
});
module.exports = router;