I created a simple project , by running npm init.
Now I got a folder
backend ->httpserver.js ->package.json
Inside, httpserver.js i had as below
var http = require("http");
//create a server object:
http
.createServer(function (req, res) {
res.writeHead(200, { "Content-Type": "text/html" }); // http header
var url = req.url;
if (url === "/about") {
res.write("<h1>about us page<h1>"); //write a response
res.end(); //end the response
} else if (url === "/contact") {
res.write("<h1>contact us page<h1>"); //write a response
res.end(); //end the response
} else {
res.write("<h1>Hello World!<h1>"); //write a response
res.end(); //end the response
}
})
.listen(3000, function () {
console.log("server start at port 3000"); //the server object listens on port 3000
});
It worked perfect. WITHOUT DOING NPM INSTALL FOR HTTPSERVER To my surprise, it worked even without a nodemodules folder.
But now, i removed the httpserver.js and added expserver.js which contains the below.
const express = require("express");
const app = express();
app.listen(8000, () => {
console.log("Server running at 8000");
});
but this is erroring , "Cannot find module express"
I know i can do npm install to resolve it. But why dint it error out for httpserver ? Kindly help
CodePudding user response:
http
is a built-in module, so you can just require()
it without having to install it.
express
is not a built-in module so you have to first install it before you can require()
it.
There are a significant number of built-in modules which you can see listed in the documentation. Any other 3rd party modules like Express you would have to install from NPM (or some other module source).
npm install express