Building your first Node.js Application
So, you have learnt Javascript, and now wanna move to building backend of web applications. Let me introduce you to Node.js. It is a Javascript runtime environment used for running web applications outside the browser.
In this article, i will help you to get started with running your first web application using Node.js and Express.
Prerequisites
- Install the latest version of Node.js from the official website.
- A code editor of your choice.
Setting up the development environment
Create a new project directory and initialize it in your code editor:
- Open the terminal and run the command
npm init
to create thepackage.json
file, which will contain all the dependencies of the project. - Use the command
npm install express
to install Express.
Creating a Server
After setting up the development environment, create two files named app.js
and server.js
.
In the app.js
file:
- Import the Express module using the following code:
const express = require("express");
2. Initialize an Express application:
const app = express();
3. Export the app module:
module.exports = app;
In the server.js
file:
- Import the app module:
const app = require("./app");
2. Set up the application to listen on a specific port:
const port = 3000;
const server = app.listen(port, () => {
console.log(`Server has started on port ${port}`);
});
Running Your Application
Time to start up your first Node and Express application. Run the command node server.js
to run the application. Your application should be running on port 3000.
Conclusion
This article has equipped you with information to start your first node.js application. You learnt how to set up the development environment and create a web server. You can now build upon this to create more complex applications tailored to your interests.