What is Node.js?
Node.js uses to create a backend using javascript. In a simple way, Node.js is a javascript complier/interpreter which is used to run javascript outside of the browser.We can use Node.js to create Server-side applications(API, Web server) and Desktop applications like Atom.
If Node is not installed in your computer, check this link to download.
The most useful feature of Node is that it comes pre-installed with package manager called NPM(Node Package Manager). There are thousands of packages in Node and NPM gives access to all of the packages. One of the package we need for setting up localhost is Express.
To install a package using the command line:
npm install package-name
Steps to create a localhost:
- Create a server.js file in your root directory.
- Install Express using the command
npm install express
- In server.js file,
// Express to run server and routes
const express = require('express');
// set up an instance of app
const app = express();
// Initialize the main project folder(remember to save all html,css,js files into this folder)
app.use(express.static("folder_name"));
// Initialize the route with callback function
app.get("/", sendData);
// Callback function
function sendData(request,response) {
response.sendFile(path.join(__dirname + '/index.html'));
}
// Initialize port
const port = 3000;
// Spin up the server
const server = app.listen(port,listening);
function listening() {
console.log(`running in localhost: ${port}`);
}
require() function is used to import the express module.
To learn more about Express:
Express
Top comments (0)