I am having a very strange crash in nodejs, the error is
Error: listen EADDRINUSE :::3000
at Object.exports._errnoException (util.js:1020:11)
at exports._exceptionWithHostPort (util.js:1043:20)
at Server._listen2 (net.js:1258:14)
at listen (net.js:1294:10)
at Server.listen (net.js:1390:5)
at Object.<anonymous> (C:\Users\tyler\Desktop\workspace\stream pop-up\index.js:18:6)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
and my code is
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require("fs");
var port = process.env.PORT || 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/popup.html');
});
fs.watchFile("assets/popup.json", {interval:100}, function(curr, prev)
{
console.log("working")//dosen't go here
fs.readFile("assets/popup.json",{encoding:"utf8"}, function(err, data){
io.emit("popup", data)
})
});
http.listen(port, function()
{
console.log("working")//doesn't go here
console.log('listening on *:' + port);
});
console.log("working") //this one prints
the exact same code was working a before, the only difference was I put this file, along with the node_modues in a subfolder, and then took them out of that subfolder, because I was getting the same error. I have no idea why this is happening, and any help would be appreciated
edit: I now know that the problem is the port is in use, but I don't know why. I tried using a python script subprocess.Popen t call this script, but it errored out after the next line of code was ran (the creation of a tkinter window)
The port 3000 is already in use, you could try to change port 3000 to some other port or kill the instance running in the port 3000.
on mac and linux
killall node
on windows
taskkill /f /im node.exe
Your port 3000 already in use. Try to change port 3000 or kill the script running in this port.
If you are using Linux or Unix, try to run this command to verify port is in use:
sudo lsof -i -P -n | grep LISTEN
Or in Windows:
netstat -a -b
Related
I have a simple REST API using MEAN. It's hosted on Heroku, and everything works well there. However, if I try to run it on localhost I get the following error:
TypeError: Parameter "url" must be a string, not undefined
at Url.parse (url.js:81:11)
at Object.urlParse [as parse] (url.js:75:5)
at module.exports (/Users/ricardotaboada/Desktop/sbackend/node_modules/mongodb/lib/url_parser.js:15:23)
at connect (/Users/ricardotaboada/Desktop/sbackend/node_modules/mongodb/lib/mongo_client.js:403:16)
at Function.MongoClient.connect (/Users/ricardotaboada/Desktop/sbackend/node_modules/mongodb/lib/mongo_client.js:227:3)
at Object.<anonymous> (/Users/ricardotaboada/Desktop/sbackend/server.js:15:21)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
Any idea what's going on? Thanks very much.
EDIT: Here is the code that connects to Mongo:
mongodb.MongoClient.connect(process.env.MONGODB_URI, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
sbrdcontroller = new controller(database);
console.log("Database connection ready");
// Initialize the app.
var server = app.listen(process.env.PORT || 3000, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
Hard to say without seeing some code.
That said, from the error message it sounds like you're not passing a valid URL to connect to your mongodb.
EDIT:
Right, so based on your code, check the value of process.env.MONGODB_URI. You can do that from your heroku account or cli, or by console.log, but I'm betting it's not set on your heroku app. Depending on the Mongo addin you use, they use different environment variable names.
process.env.MONGODB_URI is undefined in your local environment which is why the error is being thrown.
Add this code before the database connection code:
var development = process.env.NODE_ENV !== 'production';
var mongo_url;
if (development) {
mongo_url = 'mongodb://localhost:27017/mydb';
}
else {
mongo_url = process.env.MONGODB_URI;
}
Then change:
mongodb.MongoClient.connect(process.env.MONGODB_URI, function (err, database) {
To:
mongodb.MongoClient.connect(mongo_url, function (err, database) {
Assuming your local Mongo database port was not changed, the local URL with port 27017 should work fine.
Now your code should work fine in both development and production.
Maybe dotenv module will be useful for you:
https://www.npmjs.com/package/dotenv
I'm trying to run a basic node.js file on an aws server running ubuntu 14.04 and apache 2.4.7
var http = require('http');
var hostname = '33.33.33.33';
var port = 3000;
var server = http.createServer(function(req, res) {
console.log(req.headers);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello World</h1>');
});
server.listen(port, hostname, function() {
console.log('Server running at http://${hostname}:${port}/');
});
The hostname is just the IP to the server. Should it be something else? Should the hostname be the IP or should it be something else?
The above code gives the following error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRNOTAVAIL
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1020:19)
at listen (net.js:1061:10)
at net.js:1135:9
at dns.js:72:18
at process._tickCallback (node.js:415:13)
at Function.Module.runMain (module.js:499:11)
at startup (node.js:119:16)
at node.js:901:3
********Update*********
I have updated my code with localhost. That got rid of the error and allowed me to run the .js file. However I can't access the file from the server. I type in the IP like so
**.**.**.**:3000
This returns the message:
This site can’t be reached
**.**.**.** refused to connect.
ERR_CONNECTION_REFUSED
I also try accessing the location the file is located on the server but I get the same result.
**.**.**.**:3000/nodelearning/c1_node_week1/node-express
After I run:
node myNodeApp.js
In the terminal, I just need to access the IP of the server from a web browser right? Do I need to access only the root **.**.**.**:3000 or do I need to access the specific location of the node file **.**.**.**:3000/learningNode/myNodeApp.js
I only need to access the root right?
So **.**.**.**:3000 should work?
Below is the .js file that I'm able to run. But I can't access.
var express = require('express'),
http = require('http');
var hostname = 'localhost';
var port = 3000;
var app = express();
app.use(function (req,res, next) {
console.log(req.headers);
res.writeHead(200, {'Content-Type': 'text/html' });
res.end('<html><body><h1>Hello World</h1></body></html>');
});
var server = http.createServer(app);
server.listen(port, hostname, function(){
console.log('Server running at http:// NVM');
});
Cheers
the issue is with
var hostname = '33.33.33.33';
because when routes are recycled new ip address are assigned to the machine. so this will fail. As a recomendation skip host parameter in listen() or if you still want to use hostname use
var hostname = '127.0.0.1';
or
var hostname = 'localhost';
hope it helps :)
I know my question is repeated. Please read the question completely before marking as duplicate or anything.
I am learning node.js to create rest api & doing great on it.Everything was going smooth till i found this error( EADDRINUSE) on restart the app. This issue eat my precious hours but still not able to find the correct fix.
If the application is running for the 1st time, it launch's smoothly with out any port change for some reason we stop or restart the app this error message while be thrown from the server. Many of them suggested just change the port everything work smooth and I do agree with them.But When server is live & used worldwide you can't change the port to restart.
Adding Snippet of my Code.
app.js
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var config = require('./Config/config.js');
var api = require('./apis/api');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
app.all('/api/write/'+config.WRITE_API_VERSION+'/:apiName', function (req, res) {
api.handle.apply(null, ['write', req.method.toLowerCase(), req.params.apiName, req, res]);
console.log("in api end1"+req.body);
});
app.all('/api/read/'+config.READ_API_VERSION+'/:apiName', function (req, res) {
api.handle.apply(null, ['read', req.method.toLowerCase(), req.params.apiName, req, res]);
console.log("in api end2");
});
app.use(function (req, res, next) {
res.contentType('application/json');
next();
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(config.PORT);
console.log('Magic happens on port ' + config.PORT);
config.js
var configs = {
ENVIRONMENT: "development",
READ_API_VERSION: "v1.0",
WRITE_API_VERSION: "v1.0",
PORT: 8080
}
Object.freeze(configs);
module.exports = configs;
Package.json
"scripts": {
"start": "node app.js"
}
Error Message
node app.js
Magic happens on port 8080
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1039:14)
at listen (net.js:1061:10)
at Server.listen (net.js:1135:5)
at EventEmitter.listen (/home/ubuntu/vcare_backend/VCare/node_modules/express/lib/application.js:617:24)
at Object.<anonymous> (/home/ubuntu/vcare_backend/VCare/app.js:47:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
After running the command sudo netstat -plnt
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 3277/node
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1073/sshd
tcp6 0 0 :::22 :::* LISTEN 1073/sshd
Your issue is that node is already running on port 8080. This is shown by the first line returned by the netstat/lsof command. Killing the process will allow you to restart the node process. You can do this on a mac by using the command
killall node
Where node is the name of the process.
Node is already running on your machine.
In Terminal, find the running Node process with
ps -ax | grep node
This will return a list of the running node processes. The first column in the resulting list of processes is the process id (pid).
Kill the running node process with
kill -9 <pid>
This will kill the node process and free up the port for you to run your server.
Project running on a Node.js Server:
I'm going crazy over here. I can't figure out why I am getting a 503 error when I have done exactly what Open Shift instructs to do.
Server.js:
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
server.listen(server_port, server_ip_address, function(){
console.log("Listening on " + server_ip_address + ",
server_port " +server_port);
});
package.json:
{
"scripts": {
"start": "supervisor server.js"
},
"main": "server.js"
}
I have gone through my logs and everything, and it says there is an issue at line 5 on server.js. How is that so? Am I going crazy, or am I missing something? The NPM modules are cleared, and the application says it is fine.
This is not a replica of another post, because I have done all of those.
Server Log Trail Error:
ReferenceError: server is not defined
at Object.<anonymous> (/var/lib/openshift/550764f6e0b8cd8a8a00007e/app- root/runtime/repo/server.js:4:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
DEBUG: Program node server.js exited with code 8
DEBUG: Starting child process with 'node server.js'
/var/lib/openshift/550764f6e0b8cd8a8a00007e/app- root/runtime/repo/server.js:4
server.listen(server_port, server_ip_address, function(){
^
I have no idea what is going on. I keep getting a server is undefined issue, and everything is done correctly from what I can see.
You have a string opened at the end of line 5 and you never close it. change it to
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
server.listen(server_port, server_ip_address, function(){
console.log("Listening on " + server_ip_address
+ ", server_port " + server_port);
});
and you should be good to go
If that is what your file actually looks like, it looks like you are missing a chunk of code:
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write("Welcome to Node.js on OpenShift!\n\n");
response.end("Thanks for visiting us! \n");
});
server.listen( port, ipaddress, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
That code is referenced from this quickstart: https://github.com/openshift-quickstart/openshift-nodejs-http-and-websocket-example/blob/master/server.js
The references server.js includes some websocket code also, but you can ignore that (unless you want to use it, that's fine too)
I have been trying to fix this for hours, with endless googling, I try to start the app, go to the url and see a 503 Service Unavailable error, I then cd into app-root/repo, try to manually start server.js, and get the following:
[my-app-url.rhcloud.com repo]\> node server.js
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
Connecting to server
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1039:14)
at listen (net.js:1061:10)
at net.js:1143:9
at dns.js:72:18
at process._tickCallback (node.js:415:13)
at Function.Module.runMain (module.js:499:11)
at startup (node.js:119:16)
at node.js:902:3
This is driving me insane, all I'm trying to do is a simple api, and it works perfectly in my local environment.
Thank you.
Already another program or instance of this program is running on same port.
run - sudo netstat -tapen | grep ":<<your given port>>"
and then kill the process.
Then try to run the server...
Thanks
You need to bind to the OPENSHIFT_NODEJS_IP, i see you are only binding to the correct port, not the ip also: https://developers.openshift.com/en/node-js-getting-started.html
https://github.com/openshift-quickstart/openshift-nodejs-http-and-websocket-example/blob/master/server.js#L1
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var WebSocketServer = require('ws').Server
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write("Welcome to Node.js on OpenShift!\n\n");
response.end("Thanks for visiting us! \n");
});
server.listen( port, ipaddress, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
wss = new WebSocketServer({
server: server,
autoAcceptConnections: false
});
wss.on('connection', function(ws) {
console.log("New connection");
ws.on('message', function(message) {
ws.send("Received: " + message);
});
ws.send('Welcome!');
});
console.log("Listening to " + ipaddress + ":" + port + "...");