access application port : express - node.js

I am trying to build a simple chat application with node.js using Express.My node version is v0.12.7 and express version is 4.13.1.
I need to access the port the application is listening to but I am not getting how to do that even after lot of research over google.
My code in index.js is:
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
io.on('connection', function(socket){
console.log('a user connected');
});
console.log(app.get('port')); // not working
http.listen(app.get('port'), function(){
console.info('Server listening on port :');
});
module.exports = router;
Please suggest If this can be done and how. Thanks in advance :)

In order to get the port, you're going to have to set it first like this
var app = require('express')();
app.set('port', process.env.PORT || 3000);
...

Related

Why is DEBUG not logging in the console?

I am trying to take a tutorial on node.js and express. I'm trying to use the debug feature, but it is not logging anything to the console.
console.log works fine...but using debug() does not
I am on windows and am trying to run the app with...
set DEBUG=app ; node app.js
var express = require('express');
var chalk = require('chalk');
var debug = require('debug')('app');
var app = express();
app.get('/', function(req, res){
res.send('Hello from my library app');
})
app.listen(3000, function(){
debug(`listening on port ${chalk.blue('3000')}`);
});
Try this:
var express = require('express');
var chalk = require('chalk');
var app = express();
var debug = require('debug')(app);
app.get('/', function(req, res){
res.send('Hello from my library app');
})
app.listen(3000, function(){
debug(`listening on port ${chalk.blue('3000')}`);
});

What does require('express')() do in NodeJS

As far as I understand, require('express')() doesn't create a server, it just bundles the functions together. But if so, how does the following code run without server?
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
Also, if it does create a server, why do I need to import http module and manually create a server in the following example?
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
I am very confused. Thanks in advance.
require('express')() creates an instance of an Express application.
It's short for this:
var express = require('express');
var app = express();
You don't need to explicitly use http if you want to create an HTTP server, because Express will create one for you if you call app.listen().
If you need that server for something else, for instance, to attach a socket.io instance to, you can use this:
var express = require('express');
var app = express();
var server = app.listen(3000, ...); // returns an `http.Server` instance
var io = require('socket.io')(server);
Basically when you do require('express'), it imports a function. The following () calls the function as well. Basically it instantiates an express app.

error in code while running in nodejs

var express = require('express'),
app = express.createServer();
app.use(express.logger());
app.get('/', function(req, res){
res.send('Hello World');
});
app.listen();
console.log('Express server started on port %s', app.address().port);
I get the error "unexpected identifier"
what is wrong with the code?
I don't think there's a method createServer in express. This is from their docs:
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(3000);
http://expressjs.com/en/starter/hello-world.html
express.createServer() has been deprecated. Please check this question
Nodejs / Express - Launching my app: express.createServer() is deprecated
on how to update the project to work with more recent versions of express.
You didn't declare port anywhere and also you didn't mention the port number also.When you are using app.address().portit does not hold any port value so that's why it returns undefined.Here is my code hope this helps for you.Just save this code with a name I saved it as server.js
var http=require('http');
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 8000);
app.get('/', function(req, res){
res.send('Hello World');
});
var server = http.createServer(app);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
OUTPUT IN TERMINAL:
C:\Users\nodejs\tasks>node server.js
Express server listening on port 8000
Open a browser and type localhost:8000 then
OUTPUT IN BROWSER:
Hello World

Access the public folder when using node and Express?

I have looked through stackoverflow and read the express documentation, I can't figure out why the app won't run when I implement "app.use(express.static());" does anyone know a fix?
var express = require('express')();
var app = require('express')();
var server = require('http').Server(app);
var io = require("socket.io").listen(server);
//If i use this my app will not start
// app.use(express.static());
app.get('/', function(req, res){
res.sendfile('index.html');
});
//Get input from front-end
io.on('connection', function(socket){
// On input do something
socket.on('directional in', function(unique_id, input, input1){
// send info to index
io.emit('directional out', unique_id, input, input1);
});
});
server.listen(3000, function(){
// Server is running
console.log('listening on *:3000');
});
Any help would be great!
You're not initialising express correctly. The correct way would be as follows:
var express = require('express');
var app = express();
With this, you will be able to do
app.use(express.static(__dirname + '/public'));
All together, a fully functional express app would look like this in its most basic form:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 3000);
Let me know what happens.

Nodejs include socket.io in router page

I have an express node app, and I'm trying to keep my code neat by not having all the socket.io stuff in app.js
I don't know the best way to go about this. Here is my initial thought which doesn't feel like the cleanest one
// app.js
var express = require('express')
, app = express()
, server = require('http').createServer(app)
, url = require('url')
, somePage = require('./routes/somePage.js')
, path = require('path');
app.configure(function(){...});
app.get('/', somePage.index);
and the route
// somePage.js
exports.index = function (req, res, server) {
io = require('socket.io').listern(server)
res.render('index',{title: 'Chat Room'})
io.sockets.on('connection', function(socket) {
...code...
}
}
I feel like I'm close but not quite there
I don't know if I'm reading that right but it looks like you are starting a socket server on every request for /, which I'm frankly a little surprised works at all.
This is how I'm separating out the socket.io code from app.js (using express 3.x which is a bit different than 2.x):
// app.js
var express = require('express');
var app = express();
var server_port = config.get('SERVER_PORT');
server = http.createServer(app).listen(server_port, function () {
var addr = server.address();
console.log('Express server listening on http://' + addr.address + ':' + addr.port);
});
var sockets = require('./sockets');
sockets.socketServer(app, server);
// sockets.js
var socketio = require('socket.io');
exports.socketServer = function (app, server) {
var io = socketio.listen(server);
io.sockets.on('connection', function (socket) {
...
});
};
Hope that helps!
a similar approach is to pass app into index.js file and initiate http and socketio server there.
//app.js
//regular expressjs configuration stuff
require('./routes/index')(app); //all the app.get should go into index.js
Since app is passed into index.js file, we can do the app.get() routing stuff inside index.js, as well as connecting socketio
//index.js
module.exports = function(app){
var server = require('http').createServer(app)
,io = require('socket.io').listen(server);
app.get('/', function(req, res){
});
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
io.sockets.on('connection', function(socket){
socket.on('my event', function(data){
console.log(data);
});
});
io.set('log level',1);
//io.sockets.emit(...)

Resources