What is the purpose of this? var http = require('http') - javascript

I'm super new to server-side, so apologies for such a basic question.
I was looking at an example of a Node/Express server file in this blog post and came across this:
var http = require('http')
What is the purpose of requiring 'http'? It doesn't seem to be any kind of dependency. Is this something from Express/Node? Could someone please explain?

'http' is a core module in node.js.
Node.js needs to create http/https servers, hence we have to import the http module in order to create an HTTP Server.
Thus,
var http = require('http')
is just to import the built-in http module, so that we can create http server which will respond to our requests. After importing the module, a server can be created by using the createServer() method offered by http module.
var server = http.createServer(handleRequest);
For more detailed info, visit https://nodejs.org/api/http.html

You’ll use Node’s require function to use the http module. require is similar to keywords like import or include in other languages. require takes the name of a package as a string argument and returns a package. There’s nothing special about the object that’s returned—it’s often an object, but it could be a function or a string or a number.
var http = require('http')
Node has a built-in module called http. It is useful for building web applications. and by using the above code you are getting all things those are exposed by http module.
It's like creating object of a class and getting access of all the properties(Variable and Functions)of that class.

To use the HTTP server and client one must require('http').
It is an API provided by Node.js. If you want to know more on this, https://nodejs.org/api/http.html

It doesn't seem to be any kind of dependency
But it is. Further down in the example there's this line:
var server = http.createServer(app).listen(port, function() { ...
which requires http to work. You probably missed it.

Related

Is it a normal to make http request on node.js

I'm using SSR with react and i18next. I don't have a lot experience with Node.js, so the question is:
Is it a normal way to make an external http request in a start of a server script execution and pass all the left server script code into the then function of a returned Promise instance as a later continuation part of the script.
Server code which is bundled and then is started
server.js
import express from 'express';
import promiseRequest from 'request-promise';
import i18next from "i18next";
import middleware from "i18next-express-middleware";
import render from './render';
const app = express();
promiseRequest.get('https://api/localization')
.then(data => {
i18next.use(middleware.LanguageDetector);
i18next.init();
app.use(middleware.handle(i18next));
app.listen(3000, () =>
console.log('App is running')
);
return app;
});
The reason I go this way is because I need to init i18n based on a response from a server.
Why do you need to make an api request to figure out your localization needs? Wouldn't that be a part of the incoming request to your static server (gimme the website in english, french, etc)? I'm unclear about your use case. Are you trying to have several instances of your static server to serve different languages?
A common model I've seen is to have multiple static files pre-generated, per localization, and then serve them up based on the request, ex: have a route that returns the english version when the user makes a request to http://yourwebsite.com/en, the french one at http://yourwebsite.com/fr or http://yourwebsite.fr, etc.

Does NodeJS's https module follow redirects?

I'm using the NodeJS https module to fetch pages and process them during testing. I can't find any mention of following redirects either there or in the http module documentation.
From experience I would assume that an https.request does not automatically follow redirects (through response.headers.Location), but I'd like to be sure.
Nodejs doesn't follow redirects by default.
The following article explains this http://syskall.com/how-to-follow-http-redirects-in-node-dot-js/

Restify middleware like express middleware specifying route

I need to use restify middleware system just like express middleware, but it doesn't seem to work since restify needs only a callback when using
server.use(callback)
Express allows us to make something like :
server.use(patternConcerned, callback)
So, when the request will match the patternConcerned, the server will execute the middleware call.
Does it exist something similar using restify ?
No, Restify do not allow the creation of sub-application.
You're code doesn't work because Restify server.use(callback) instantiate a new middleware on your entire application while Express server.use(patternConcerned, callback) instantiate a new middleware on a sub-application.

Why do I need to pass an express server instance as a parameter to the http module in Node.JS?

I'm currently studying Node.JS, Express.JS and Socket.IO. The tutorials that I've seen so far use a complicated sequence of code in order to initialize each of those modules:
var express = require("express");
var app = express();
var server = require("http").createServer(app);
var io = require("socket.io")(server);
Why is the variable "app" passed as a parameter to the variable "server" and server passed as a parameter to "io"?
Thank you in advance.
express (which is not part of node.js) is implemented as a request listener with which you can initiate the http server implementation provided by node.js.
Check the docs:
https://nodejs.org/api/http.html#http_http_createserver_requestlistener

socket.io.js not loading

I know there are a bunch of questions on this already, but none have answered it for me, and plus mine is slightly different.
I'm starting the socket.io server in node using this:
var io = require('socket.io').listen(8000);
My terminal says everything is ok:
info - socket.io started
Now I am trying to load the .js file in my clientside browser using this url:
http://<hostname>:8000/socket.io/socket.io.js
I dont get a 404, it just hangs forever. I've also used a network utility to ping port 8000, and it seems to be open fine.
I installed node and socket.io just yesterday, so they should be the latest versions. Can anyone shed any light on this? Thanks!
Turns out the reason I could never request the .js file was because my company network blocks all ports except the usual ones (80, 21, etc), so `I would never be able to communicate with port 8000.
Use express.js. Place the socket.io file in public/javascripts folder and add this line to your html
<script src="/javascripts/socket.io.js"></script>
I think this is the best way. When you're writing http://<hostname>:8000/socket.io/socket.io.js
node tries to find a folder named socket.io in your project's public folder. And the file socket.io.js in it.
If you don't want to use express.js you should catch the request and try to load a file if no routes were found for your request (what actually express does) because node doesn't know what to do for requests which don't match any routes in your server.
And I recommend to use the socket.io.min.js file (it's smaller and it's in folder node_modules\socket.io\node_modules\socket.io-client\dist)
You have to start an http/https server to access it via http/https. Simply starting an socket.io server won't do. Do the following:
var http = require('http');
var app = http.createServer(),
io = require('socket.io').listen(app);
app.listen(7000, "0.0.0.0");
Then I can access the file http://localhost:7000/socket.io/socket.io.js
sockets.io uses websocket protocol (ws://). See the wikipedia page.
You need to get at least 3 pieces working together.
Serve some HTML (/index.html will do just fine) so there's a web page. This file should contain the socket.io client <script> tag. For this you need the http server portion of the starter examples. You are missing this and that's why browsing to your server just hangs.
Serve the socket.io client. Socket.io will do this for you automatically when you pass in your http server function to it. You don't need full express as this can be done with just node's http module as per the first example on the socket.io docs.
Some javascript to actually do something with the socket. This can be the content of a <script> tag in index.html or a separate file. If it's a separate file, you need to set up your http server to actually serve it.

Categories