Hey Guys I am running this an API generator with node with this,
var cluster = require('cluster');
if (cluster.isMaster) {
// first set up logging for the master
var logger = require("./api/helpers/logging.js")();
var num_cpus = require('os').cpus().length;
logger.debug(num_cpus + " <-- that many CPUs detected!");
// create a fork for each CPU (or "thread" for Intel CPUs...)
for (var i = 0; i < num_cpus; i++) {
cluster.fork();
}
// if one of the forks dies, spawn a replacement!
cluster.on('exit', function (worker, code, sig) {
var report = ('Worker '+worker.process.pid+' died... Creating a new one!\n');
report += (' -- code: '+code+'\n');
report += (' -- sig: '+sig+'\n');
logger.warn(report);
cluster.fork();
});
cluster.on('uncaughtException', function(error) {
logger.error(error);
process.exit();
});
}
else {
var http = require("http");
var app = require("./api/do_api.js");
http.createServer(app).listen(app.get('port'), function () {
// console.log('Express server listening on port ' + app.get('port'));
});
}
This runs perfectly with node thefile.js and generates my endpoints as needed, though I am having an issue integrating it into my grunt serve if I try just "dropping" the require() into my server.js I end up with multiple address in use errors such as the following
events.js:72
throw er; // Unhandled 'error' event
^
Error: bind EADDRINUSE
at errnoException (net.js:901:11)
at net.js:1073:26
at Object.25:1 (cluster.js:587:5)
at handleResponse (cluster.js:171:41)
at respond (cluster.js:192:5)
at handleMessage (cluster.js:202:5)
at process.EventEmitter.emit (events.js:117:20)
at handleMessage (child_process.js:318:10)
at child_process.js:392:7
at process.handleConversion.net.Native.got (child_process.js:91:7)
connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
debugger listening on port 5858
connect.limit() will be removed in connect 3.0
debugger listening on port 5858
events.js:72
throw er; // Unhandled 'error' event
^
Error: bind EADDRINUSE
at errnoException (net.js:901:11)
at net.js:1073:26
at Object.23:1 (cluster.js:587:5)
at handleResponse (cluster.js:171:41)
at respond (cluster.js:192:5)
at handleMessage (cluster.js:202:5)
at process.EventEmitter.emit (events.js:117:20)
at handleMessage (child_process.js:318:10)
at child_process.js:392:7
at process.handleConversion.net.Native.got (child_process.js:91:7)
Contents of my server.js are like this
'use strict';
var express = require('express'),
path = require('path'),
fs = require('fs'),
mongoose = require('mongoose');
/**
* Main application file
*/
// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
// Application Config
var config = require('./lib/config/config');
// Connect to database
var db = mongoose.connect(config.mongo.uri, config.mongo.options);
// Bootstrap models
var modelsPath = path.join(__dirname, 'lib/models');
fs.readdirSync(modelsPath).forEach(function (file) {
if (/(.*)\.(js$|coffee$)/.test(file)) {
require(modelsPath + '/' + file);
}
});
// Populate empty DB with sample data
require('./lib/config/dummydata');
// Passport Configuration
var passport = require('./lib/config/passport');
var app = express();
// Express settings
require('./lib/config/express')(app);
// Routing
require('./lib/routes')(app);
require('./thefile.js'); // this is the kicker file shown above
// Start server
app.listen(config.port, function () {
console.log('Express server listening on port %d in %s mode', config.port, app.get('env'));
});
// Expose app
exports = module.exports = app;
How can I get this to work?
You're using listen both in server.js and do_api.js. You need to start listening for requests only once.
You have this error because you can't listen on the same host and port from more than one process. Even if you removed the duplicate call to listen, this won't work unless each cluster runs in its own environment: they either listen to the same port on different hosts, or they listen to different ports on the same host, or (probably what you want) they serve as workers for a single request listener in a single host/port combination.
Related
I am trying to write a node service that listens on a port and writes to the Event log, but I can't connect when I launch a browser at http://localhost:41414/?x=y Im not getting event records from the listener file (which launches the express server). Any idea what I'm doing wrong?
I created a service using node-windows: launch using (node mysvc.js --install 42424)
var Service = require('node-windows').Service;
//-----------------------------------------------init vars
// Create a new service object
var svc = new Service({
name:'My Listener v1.1',
script: require('path').join(__dirname,'listener.js '+port)
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
svc.start();
});
// Listen for the "uninstall" event so we know when it's done.
svc.on('uninstall',function(){
console.log('Uninstall complete.');
console.log('The service exists: ',svc.exists);
});
//-------------------------------------------------------end init vars
var port=0;
if(process.argv[2]=="--uninstall")
svc.uninstall();
else if(process.argv[2]=="--install")
if(parseInt(process.argv[3])>0){
port=parseInt(process.argv[3])
svc.install();
}
else{
console.log('must pass --install or --uninstall flag')
return;
}
listener.js starts listening on the port:
const express = require('express');
var EventLogger = require('node-windows').EventLogger;
var log = new EventLogger('My Listener');
port=41414
app.get('/data', (req, res) => {
const jdata = req.params[0];
log.info(jdata+' WOOOOO!!!!');
})
log.log(`Service listening on port ${port}`);
app.listen(port);
you just missing this line in your listener.js
const app = express()
I have a node application that is not working though did work about 2 hours ago (no code changes). Also no changes to the server, I only ran another node application on the same port but that process has been killed.
Command to start node node server
server.js
var app = require('./server/index');
app.set('port', process.env.PORT || 3000);
var server = app.listen(8080, function() {
console.log('Express server listening on port ' + server.address().port);
});
app.js (stripped down)
const express = require("express"),
mongoose = require("mongoose"),
app = express();
mongoose.connect(config.db, {autoReconnect: true}, (err) => {
if (!err) console.log('MongoDB has connected successfully.');
});
mongoose.connection.on('error', function() {
console.error('MongoDB Connection Error. Make sure MongoDB is running.');
});
var authRoutes = require('./routes/auth.js');
authRoutes(app, passport);
module.exports = app;
Output when starting node process
(node:4341) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:4341) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
MongoDB has connected successfully.
Solved it, seems that using node server was going directly into my server directory and running app.js file note the server.js file I wanted it to. Instead I had to run node server.js
Nodejs is very weird for me dealing with asynchronous. I heavily used the structure from https://github.com/elad/node-cluster-socket.io. My biggest issue is the lack examples and documentation to handle clustering.
Code:
var config = require(__dirname+'/Config/config.json');
var sql = require(__dirname+'/Server/mysql.js');
var express = require('express'),
cluster = require('cluster'),
net = require('net'),
sio = require('socket.io'),
sio_redis = require('socket.io-redis'),
farmhash = require('farmhash');
var fs = require('fs');
var https = require('https');
var options = {
key: fs.readFileSync(__dirname+'/Config/key.pem'),
cert: fs.readFileSync(__dirname+'/Config/server.crt')
};
var app = express();
var num_processes = require('os').cpus().length;
if (cluster.isMaster) {
console.log('master online');
// This stores our workers. We need to keep them to be able to reference
// them based on source IP address. It's also useful for auto-restart,
// for example.
var workers = [];
// Helper function for spawning worker at index 'i'.
var spawn = function(i) {
workers[i] = cluster.fork();
// Optional: Restart worker on exit
workers[i].on('exit', function(code, signal) {
console.log('respawning worker', i);
spawn(i);
});
};
// Spawn workers.
for (var i = 0; i < num_processes; i++) {
console.log('Worker Spawned');
spawn(i);
}
// Helper function for getting a worker index based on IP address.
// This is a hot path so it should be really fast. The way it works
// is by converting the IP address to a number by removing non numeric
// characters, then compressing it to the number of slots we have.
//
// Compared against "real" hashing (from the sticky-session code) and
// "real" IP number conversion, this function is on par in terms of
// worker index distribution only much faster.
var worker_index = function(ip, len) {
return farmhash.fingerprint32(ip) % len; // Farmhash is the fastest and works with IPv6, too
};
app.get('/',function(req, res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use('/client',express.static(__dirname + '/client'));
// Create the outside facing server listening on our port.
//var serv = https.createServer(options, app);
var server = https.createServer(options, app);
//var server = net.createServer({ pauseOnConnect: true }, function(connection) {
// We received a connection and need to pass it to the appropriate
// worker. Get the worker for this connection's source IP and pass
// it the connection.
//var worker = workers[worker_index(connection.remoteAddress, num_processes)];
//worker.send('sticky-session:connection', connection);
//console.log('Socket Connection!'+worker_index(connection.remoteAddress, num_processes));
server.listen(config.ServerPort);
var io = require('socket.io')(server,{});
io.sockets.on('connection', function(socket){
console.log('Socket Connection');
socket.on('signIn',function(data){
console.log('signin Attempt');
sql.LoginCheck(data,function(res){
if(res){
console.log('signin Success');
socket.emit('signInresponse',{success:true});
var worker =workers[1];
worker.send('sticky-session:connection', server);
console.log('Socket Connection passed');
}else{
console.log('signin Fail');
socket.emit('signInresponse',{success:false});
}
});
});
// socket.on('disconnect',function(){
// delete SOCKET_LIST[socket.id];
// console.log('socket disconnected');
// });
});
} else {
// Note we don't use a port here because the master listens on it for us.
var app = new express();
// Here you might use middleware, attach routes, etc.
// Don't expose our internal server to the outside.
var server = app.listen(0, 'localhost');
io = sio(server);
// Tell Socket.IO to use the redis adapter. By default, the redis
// server is assumed to be on localhost:6379. You don't have to
// specify them explicitly unless you want to change them.
io.adapter(sio_redis({ host: 'localhost', port: 6379 }));
// Here you might use Socket.IO middleware for authorization etc.
// Listen to messages sent from the master. Ignore everything else.
process.on('message', function(message, connection) {
if (message !== 'sticky-session:connection') {
return;
}
// Emulate a connection event on the server by emitting the
// event with the connection the master sent us.
console.log('Socket Connection received');
server.emit('connection', connection);
connection.resume();
});
}
Console
master online
Worker Spawned
Worker Spawned
Worker Spawned
Worker Spawned
Socket Connection
signin Attempt
Admin
true
signin Success
Socket Connection passed
Socket Connection received
_http_server.js:304
socket.setTimeout(self.timeout);
^
TypeError: socket.setTimeout is not a function
at Server.connectionListener (_http_server.js:304:12)
at emitOne (events.js:77:13)
at Server.emit (events.js:169:7)
at process.<anonymous> (/home/name/app/test.js:128:10)
at emitTwo (events.js:92:20)
at process.emit (events.js:172:7)
at handleMessage (internal/child_process.js:686:10)
at internal/child_process.js:497:7
at Server.<anonymous> (internal/child_process.js:57:9)
at Server.g (events.js:260:16)
respawning worker 1
No idea what to do with the error. But just doing random committing out it appears that the worker's listener is the culprit. I hope someone can help me with this.
I'm trying to build a desktop application using electron js .I want to integrate express js in my application .when I try to start my application,I'm facing this error
[Main Instruction]
A JavaScript error occured in the browser process
[Content]
Uncaught Exception:
Error: listen EADDRINUSE :::3000
at Object.exports._errnoException (util.js:814:11)
at exports._exceptionWithHostPort (util.js:837:20)
at Server._listen2 (net.js:1214:14)
at listen (net.js:1250:10)
at Server.listen (net.js:1340:5)
at EventEmitter.listen (C:\Users\Kobbi\WebstormProjects\untitled14\node_modules\express\lib\application.js:617:24)
at Object.<anonymous> (C:\Users\Kobbi\WebstormProjects\untitled14\index.js:17:18)
at Module._compile (module.js:428:26)
at Object.Module._extensions..js (module.js:446:10)
at Module.load (module.js:353:32)'
here is my code:
var BrowserWindow = require('browser-window')
var express = require('express');
var app = express();
app.use(express.static(__dirname));
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
app.on('ready', function() {
var mainWindow = new BrowserWindow({
width: 800,
height: 600
})
mainWindow.loadUrl('http://localhost:3000')
})
I would appreciate any help ,thanks in advance
app.on('ready') ... 'app' is not your express app.
this should be electron app.
Example:
var app = require('app');
BrowserWindow = require('browser-window');
express = require('express');
expressApp = express();
May be express use 'app' variable and electron also uses it.
Normally the EADDRINUSE error means, that your port is already beign used (probably by an instance of your express webserver). Maybe your electron app didn't close properly, and you have to kill to manually to also kill the webserver that is accessing the port.
I'm able to successfully run nodejs, expressjs, socket.io and mongodb appplication on my local machine http://localhost:3000
Now, I have uploaded the application on the real server that supports nodejs but how can I run the application using the port 3000? So www.mywebsite.com/MyApp:3000 doesn't work :( Do I have to run in a PORT?
can you please help me?
Here's my server app.js code:
var express = require('express');
var mongoose = require ('mongoose');
var app = express();
app.use('/', express.static('../app/'));
app.use('/bower_components', express.static('../bower_components/'));
var http = require('http').Server(app);
var io = require('socket.io')(http);
//mongodb databse
mongoose.connect ('mongodb://127.0.0.1/mydb', function (err) {
if (err) {
console.log (err);
} else {
console.log ("Connected to mongodb");
}
});
io.sockets.on ('connection', function (socket) {
console.log("hello world, I'm running fine!")
});
http.listen(3000, function () {
'use strict';
});
EDIT: if I use port 80, I get this error:
events.js:87
throw er; // Unhandled 'error' event
^
Error: listen EACCES
at exports._errnoException (util.js:748:11)
at Server._listen2 (net.js:1123:19)
at listen (net.js:1166:10)
at Server.listen (net.js:1251:5)
....etc
To run your app on production using your existing node / express code you would naviagate to http://www.mywebsite.com:3000/MyApp (assuming your firewall allows port 3000)
You can change the port though to be what ever you want by changing this part of the code:
http.listen(3000, function () {
'use strict';
});
The standard port for web is 80. So you could change this to be
http.listen(80, function () {
'use strict';
});
And then use your url as normal - http://www.mywebsite.com/MyApp
Note: If you have another web server on your server that is using this port already then you are going to have a problem as it will not listen until the port is free. You will have to disabled other web servers listening on port 80 first.
Non-privileged user (not root) can't listen on sockets on ports below 1024 either.