NodeJS is a popular framework of JavaScript used for back-end web development. And for this, a server is as important as the backbone to a human body. So in this tutorial, we'll learn how to quickly set up a nodeJS server.
First things first, make sure you're in the right directory in your CMD/Terminal/Bash. You can change directory using command 'cd', make new directory using command 'mkdir' and make new files using command 'touch'.
[NOTE: Make sure you've got NodeJS installed on your device]
Now that we're in the right directory, we need to run the npm init. It initializes the npm packages which help us to further install other packages as it creates dependencies. Its installation requires few details which right now, we'll keep empty to let the default values flow in. Once it is done, we need to install Express .
Express is a fast, unopinionated, minimalist web framework for NodeJS.
It can be installed using command
>>> npm i express --save .
Now we need to move ahead to create our server, and for that, we'll need a javaScript file where we'll write our source code. So let's create a file in terminal only.
touch index.js
Now open index.js in any text editor to start coding. You need to follow the steps now
app.get()
, we'll configure our server.app.listen()
is used to start it.const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send("Hello, I'm your server"))
app.listen(port, () => console.log(`I'm listening at http://localhost:${port}`))
Now coding our server is done. To run it, we need to run this file in terminal using node.
To check if it works or not, just go to your browser and put
http://localhost:3000
in the address bar. It'll open like this:
So that's all that it takes to create a server. Ain't it easy? Reply in community if you encounter any doubt/issue you can mention it.