Node.JS express server creation methods difference - node.js

I have recently inherited a project of a Node.JS and Express based API, and I have noticed express server creation is as such (simplified version):
// http is required.
var http = require('http');
var express = require('express');
var app = express();
// Note http is used to create server, and app is used as param:
http.createServer(app).listen(3000, function (request, response) {
console.log('listening on port 3000');
});
Everything works as expected of course.
I have been trying to figure out what exactly is happening behind the scenes here, mostly in comparison to the method in Express API, which shows:
// http is not required.
var express = require('express');
var app = express();
// Note Express is used to create the server:
var server = app.listen(3000, function () {
console.log('listening on port 3000');
})
Note the difference in server creation using http, and using Express directly.
Is there any benefit in using a specific one of the two method? What is the actual difference between the two?
Micro-optimization-wise, is it preferred to avoid requiring 'http', which is probably required by express anyway?
Thanks from ahead!

Both are more or less functionally equivalent, in the second example the express constructor returns a new object which effectively wraps up the http.createServer call internally (i.e. when you call app.listen).
If you are going to use express then you should use it's recommended APIs, the first approach is considered outdated.

Related

NodeJs - express and socket.io same port integration

I am creating a server using NodeJs and Express, but I found out that if I want to make a service live, I need to use Socket.io. In this server, there are some service that don't need to be live, and these are implemented using express routes. This are tested and correctly working. Now I have to let some services to be live. So, I think I should implement also socket.io in my server configuration. This is my code without socket.io, working perfectly:
const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.port || 5050;
app.use(morgan('dev'));
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended:true }));
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser:true});
const connection = mongoose.connection;
connection.once('open', () => console.log('Connected'));
const routes = require(#every routes);
app.use(routes);//all created routes
app.listen(port, () => {console.log(`Server listening on port ${port}`)});
NOw, I should import correctly socket.io. When it is done, I think I can figure out correctly hot to implement my services. So, I tryied to add the line const io = require('socket.io').listend(app) as I saw in another stackoverflow quesion, but the terminal shows up this error:
const io = require('socket.io').listend(app)
^
TypeError: require(...).listend is not a function
So, I don't know how to integrate this two. I don't know if it is worth to use the same port, or if I should use another port for the socket, but I think the same port would be good. If someone knows how to implement socket.io in my current code, or a way to keep both functionalities, please help me. Thank you so much
Change this:
app.listen(port, () => {console.log(`Server listening on port ${port}`)});
to this:
const httpServer = app.listen(port, () => {console.log(`Server listening on port ${port}`)});
Then, add this:
const { Server } = require("socket.io");
const io = new Server(httpServer );
This will let both your Express server and your socket.io server share the same http server. Since all incoming socket.io connections are identifiable with some custom headers, the socket.io code (actually the underlying webSocket transport does this) can grab those and handle them independently from your regular http requests.
See plenty of examples in the socket.io doc which has improved immensely from its early days.
Sometimes, it's easy to get confused looking at different examples because there are a dozen different ways to create your http server that you use with Express. The general idea here is that whichever way you use, just make sure you assign the http server instance that you created to a variable that you can then use with socket.io server initialization (as shown above). In your Express code, app is not the server. That's the Express app object which is also an http request handler. It's not the server. The server is something you get from http.createServer() or something that app.listen() returns to you (after calling http.createServer() internally).

Best Practice to create REST APIs using node.js

I am from .Net and C# background and I am new to Node.js. I am working on a project, which is mix of MongoDB and Node.JS.
In MongoDB, data from various tools is stored in different different collections. I have to create multiple REST APIs using Node.JS for CRUD operation on that data, these APIs will be called from React.JS application.
I want to keep APIs into separate files for seperate tool and then calling including all files into app.js file.
Please help me with best approach.
For POC purpose, I created a node.js application, where I created app.js file and written all my code for GET|POST|DELETE APIs. This is working fine.
var _expressPackage = require("express");
var _bodyParserPackage = require("body-parser");
var _sqlPackage = require("mssql");
var app = _expressPackage();
var cors = require("cors");
var auth = require('basic-auth');
var fs = require('fs');
const nodeMailer = require('nodemailer');
//Lets set up our local server now.
var server = app.listen(process.env.PORT || 4000, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.get("/StudentList", function(_req ,_res){
console.log("Inside StudentList");
var Sqlquery = "select * from tbl_Host where HostId='1'";
GetQueryToExecuteInDatabase(_req,_res, Sqlquery,function(err,data){
console.log(data);
});
});
Don't know exactly what your app intends to do, but usually if you are not serving webpages and your API is not too complex, there is no need to use express. You can build a simple server natively in NodeJS to serve data.
Additionally, if your app has many routes (or is likely to in the future), it is a good idea to put helper functions like GetQueryToExecuteInDatabase() in a separate file outside of app.js such as utils.js.
Based on what I have understood about what you want to do, your file structure should look something like this:
data (db related files)
services (contains one file per api service)
app.js
utils.js
Hope this helps.

Networking websockets on node.js servers

So I've been coding in web design for two weeks now and I've devolved the core for my io game on node.js just by using localhost:3000 now I'm trying to implement what I have so far into an actual web-server. It's one heck of a learning curve, so say I set up a virtual-machine in Google Cloud Platforms running node.js, socket.io what do I even set my ports too?
This is my Code currently server side:
var express = require('express'); //adds express library
var app = express();
var server = app.listen(3000); //listens on port 3000
app.use(express.static('public')); //sends the public(client data)
console.log("Server Has Started");
var socket = require('socket.io'); //starts socket
var io = socket(server);
This is my Code currently client side:
var socket = io.connect("http://localhost:3000")
my website is gowar.io and it currently resides as a static file in googles "bucket". How do I hook up my websockets with something like a virtual machine?
Typically, cloud ecosystems will give you an endpoint for your storage or allow you to configure one.
Skim through Google's Docs about WebSockets to learn more about their recommended implementation of WebSockets.

Trying to proxy with Node and express-http-proxy and failing

I'm launching NPM express in a very simple app and wanting to take what is passed into the URL and redirect it as follows. Assuming I'm listening for web traffic on 8080 and I want to proxy my rest calls to port 5000.
That is, when the URL http://localhost:3077/rest/speakers comes in, I want the results to come from http://localhost:5000/rest/speakers (where the word speakers could be sessions, attendees or any other name like that.
app = express();
app.use('/rest', proxy('http://localhost:5000/rest'));
app.listen(8080, function () {
console.log('Listening on port 8080');
});
I seem to get the result of localhost:5000 but not even sure of that.
I changed to using http-proxy-middleware and this solved my problem.
app = express();
const proxy = require("http-proxy-middleware");
const targetVal = 'http://localhost:5000/rest';
app.use(proxy('/rest', {target: process.env.DEV_RESTURL, changeOrigin:true}));

Need for http.createServer(app) in node.js / express

Using node and express, the below works just fine.
var app = express();
app.listen(app.get('port'), function() {
});
I assume that a server is created implicitly in the above construct.
When adding socket.io, I've seen the following being done.
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.listen(app.get('port'), function() {
});
What is the need for explicitly adding http.createServer(app) ? Won't the creation of an additional server mess up things ? Or put it other way, is it ok to create many more http.createServer(app) ?
In either case, only one server is created. When using socket.io, you share the same http server between socket.io and express. Both libraries attach event listeners to the same server and have a chance to respond to the same events. They cooperate nicely because socket.io only handles relevant requests and express handles all the non-websocket requests. And just FYI you could not create more than one server on the same port. Only one process can listen on a TCP port at a time in the OS, so the second one would fail with an error when attempting to bind an in-use port.

Resources