error in electron js when implementing express js - node.js

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.

Related

SyntaxError: Unexpected token const

I am creating a web server that will allow users make a request for fortunes, and get the data which I specified in my fortunes.json file. I am using express in node to do this.
I start my server this way npm run dev, however when I do so, I get the following error:
SyntaxError: Unexpected token const
at Module._compile (internal/modules/cjs/loader.js:720:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:643:32)
at Function.Module._load (internal/modules/cjs/loader.js:556:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:839:10)
at internal/main/run_main_module.js:17:11
Does anybody have an idea what I am doing wrong, my syntax, and packages.json file, etc. all seems to be fine but I am still getting this.
I am expecting to see "server listening on port 3000" when I run the server however I get a token error.
const express = require('express');
const port = 3000,
const app = express();
app.get('/fortunes', (req,res) => {
console.log('requesting fortunes');
});
app.listen(port, () => console.log('Listening on port ${port}'));
You have two issues in your code.
1 . when you are initializing variable:
As you have put ',' (comma) thus you cannot specify its declaration again.
your code
const port = 3000,
const app = express();
Do like this :
const port = 3000,
app = express();
or use this :
const port = 3000;
const app = express();
When using string template use `(backtick).
app.listen(port, () => console.log(`Listening on port ${port}`));
Try below Code:
const express = require('express');
const port = 3000,
app = express();
app.get('/fortunes', (req,res) => {
console.log('requesting fortunes');
});
app.listen(port, () => console.log(`Listening on port ${port}`));
In ECMAScript 2015, you can use backtic as follow in your code:
app.listen(port, () => console.log(`Listening on port ${port}`));
or use :
app.listen(3000, () => console.log('Connected to the port'));

Running nodejs, expressjs, socket.io application on a real server not working

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.

app.set('port' , process.env.port || 3000) typeerror object #<object> has no method 'set' at object.<anonymous>

I am using Express 4.2.0 and node.js 0.10.12.
The weird thing is that I created a project in C\program files\node\nodetest and when I did npm start I got no errors.
Now I created a project in C\program files\node\secondtest and when I do npm start I get
app.set('port' , process.env.port 3000) typeerror object #<object> has no method 'set' at object.<anonymous> and its pointing in C\program files\node\secondtest\bin\www:5:5
Truth is , I dont know how to deal with this error, because I dont get what it means. Is it because both my projects listen on port 3000?
I just started secondtest , I installed succesfully the dependencies with npm install and added this in app.js
var http = require('http');
var express = require('express');
var app = express();
http.createServer(app).listen(3000, function() {
console.log('Express app started');
});
app.get('/', function(req, res) {
res.send('Welcome!');
});
Thanks
EDIT
If I leave the default code in app.js and www I get no errors. If I replace the default code of app.js with mine, and I remove the
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
part from www, then I get no errors.
Because I guess app.set and app.get are depricated in express 4.2.0? Or because when I set an http server in my app.js code, conflicts the default www code? Either one of these, or I am really confused.
EDIT 2
This is the default code of the www
#!/usr/bin/env node
var debug = require('debug')('secondtest');
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);
});
Updated answer according to the updated question.
Since you're calling www and its code needs to set the port and listen to it, your secondtest code should not listen to the port. Instead it should export the Express app as follows:
// ...
module.exports = app;
The www will do the listening part.
Otherwise, the secondtest tries to start listening on a port while not exporting the Express app, and www tries to listen again on a variable app which is not an Express app, thus the error object #<object> has no method 'set'.
When you do var app = require('../app'); in another script, it is important so that this ../app script actually exports the Express app.
Old answer.
Do node app.js instead of using npm command.
Second, make sure the same port is not used by both processes at the same time. You can't listen to the same port unless you're in cluster mode.
Considering the following is the content of both firsttest and secondtest:
var http = require('http');
var express = require('express');
var app = express();
http.createServer(app).listen(process.env.port || 3000, function() {
console.log('Express app started');
});
app.get('/', function(req, res) {
res.send('Welcome!');
});
Do the following to start both apps:
Terminal 1: (the first app will default to port 3000).
$ node firsttest/app.js
Terminal 1:
$ export PORT=3001
$ node secondtest/app.js

Turning a Node task into a Grunt task

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.

Express module error while listening http server in nodejs

I have created a nodejs http server
var http = require("http");
var url = require("url");
var express = require('express');
var app = express();
function start(route, handle){
function onRequest(request,response){
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response, request);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started");
app.listen(8888);
console.log('Express app listening on port 8888');
}
it gives error
f:\Labs\nodejs\webapp>node index.js
Server has started
Express app listening on port 8888
events.js:66
throw arguments[1]; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:769:11)
at Server._listen2 (net.js:909:14)
at listen (net.js:936:10)
at Server.listen (net.js:985:5)
at Function.app.listen (f:\Labs\nodejs\webapp\node_modules\express\lib\appli
cation.js:532:24)
at Object.start (f:\Labs\nodejs\webapp\server.js:15:6)
at Object.<anonymous> (f:\Labs\nodejs\webapp\index.js:11:8)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
when i change the port of app.listen it dont throw this error, what can be done?
will changing port other than server port will keep the session of the server on another port??
and how can i access this app variable in other js page to get/set the data?
If you intend to run on the same port, you can see if you have currently running node processes with
ps aux | grep node
and then kill -9 PROCESSID
You can't have multiple things listening on the same port like this, hence the EADDRINUSE error. If you want to create your own http server while using Express, you can do it like this:
var express = require('express');
var https = require('https');
var http = require('http');
var app = express();
http.createServer(app).listen(8888);
https.createServer(options, app).listen(443);
From the Express docs:
The app returned by express() is in fact a JavaScript Function,
designed to be passed to node's http servers as a callback to handle
requests.
Or you can just do
app.listen(8888);
And then Express will setup an http server for you.
You would then set up your routes in Express to actually handle requests coming in. With Express, routes look like this:
app.get('/foo/:fooId', function(req, res, next) {
// get foo and then render a template
res.render('foo.html', foo);
});
If you want to access your app in other modules (usually for testing) you can just export it like any other variable:
module.exports.app = app;
You'll then be able to require('./app').app in other modules.

Resources