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.
Related
Here what exactly the var app = express(); means?
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
When the following statement is run,
var express = require('express');
the variable express gets assigned to the export value of the module express. In this case, the module exports a function, which returns some object.
So when the following statement runs,
var app = express();
the variable app gets assigned the object returned by the function.
express()-Creates an Express application. The express() function is a top-level
function exported by the express module.
Link to API doc for express:
http://expressjs.com/en/api.html
Do have look into API documents before posting questions,it might help you to understand basics.
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);
...
I am working in c9.io ide environment, I have written below code in server.js file
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var express = require('express');
var app = express();
var router = express();
var server = http.createServer(router);
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/client'));
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
res.render('index.html');
});
app.get('/about', function (req, res) {
res.send('about');
});
After running node server.js in terminal the message given as
Your code is running at https://nodejs2-mujaffar.c9.io.
Important: use process.env.PORT as the port and process.env.IP as the host in your scripts!
Server listening at 0.0.0.0:8080
But after accessing https://nodejs2-mujaffar.c9.io/ url -- It is not rendering view only displaying message Error: Cannot GET /
What I am doing wrong?
Please help.
You seem to have created two instances of express which may be your problem.
Try changing:
var express = require('express');
var app = express();
var router = express();
var server = http.createServer(router);
to:
var express = require('express');
var app = express();
var server = http.createServer(app);
At the minute, your express app variable is not bound to your http server. You have instead bounded an unused instance called router. But then you have registered your routes to the app variable.
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.
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(...)