In this article, I am showing you how to create a simple Node.js server.
What is Node.js
To learn what is Node.js and use Node.js mostly in modern applcations refer my previous article from here.
Prerequisites
* Installed Node.js
To Continue with this tutorial, you should have installed Node.js in your pc. If you are still not installed Node.js in your machine you can download it from here.
Create a project folder
First you need to create a project folder for this project. Then goto that project folder and open it in your editor and in my case it is VS code. I used VS code because it has great support on Node.js as a platform. You can find more details from here.
Create server.js file
Inside the root folder, you should make a file called server.js and paste below code in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// create new express app and save it as "app" const app = express();
// server configuration const PORT = 8080;
// create a route for the app app.get('/', (req, res) => { res.send('Hello World'); });
// make the server listen to requests app.listen(PORT, () => { console.log(`Server running at: http://localhost:${PORT}/`); });
Make sure to install express framework by running below code.
1
npm install express --save
Note: This simple server only has (/) working route. If you want to learn more about Routing, read the docs for Routing.
Run the node.js server
Now you can run our server. To run our simple server run below you command in your terminal.
1
node server.js
Result
When you run above command, you can see output like this. Server running at: http://localhost:8080/
You can click on the link and reach our server.