Starting a Node.js server is a foundational skill for any web developer looking to build and test applications in a local environment. This article is designed to walk you through the basics of setting up a Node.js server. We'll cover the essentials of running a Node.js server using vanilla Node.js and also delve into how to use Express, a widely-used Node.js framework. Additionally, we'll explain how to gracefully stop your server once it's up and running. Whether you're a beginner or just need a quick refresher, this guide will help you get your Node.js server operational in no time.
Running a Node.js Server Locally
Prerequisites
- Node.js Installed: Ensure you have Node.js installed on your machine. You can download it from nodejs.org.
Step 1: Create a Simple Node.js Server
- Initialize a Node.js Project: Create a new directory for your project and run
npm init
in your terminal to create apackage.json
file. - Create a Server File: Create a file named
server.js
. - Write the Server Code: In
server.js
, write the following code:
import http from "http";
const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader("Content-Type", "text/plain"); res.end("Hello World\n");});
const PORT = 3000;server.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}/`);});
Step 2: Run the Server
- Start the Server: In your terminal, run
node server.js
. Your server is now live athttp://localhost:3000
.
Step 3: Stopping the Server
- Stop the Server: To stop the server, simply press
Ctrl + C
in your terminal.
Running a Node.js Server with Express
Step 1: Install Express
- Install Express: In your project directory, run
npm install express
.
Step 2: Create an Express Server
- Modify server.js: Replace the content with the following:
import express from "express";
const app = express();const PORT = 3000;
app.get("/", (req, res) => { res.send("Hello from Express!");});
app.listen(PORT, () => { console.log(`Express server running at http://localhost:${PORT}/`);});
Step 3: Run the Express Server
- Start the Server: Like before, run
node server.js
. Your Express server is now accessible athttp://localhost:3000
.
Step 4: Stopping the Express Server
- Stop the Server: Use
Ctrl + C
in the terminal to stop the server.
Running a Node.js Server with RunJS
The previous options require you to install and use several separate pieces of software, but what if you could do it all with just one app?
That's where RunJS can help. It integrates Node.js and can run your code automatically. To get started, download and install RunJS. Then, run one of the code examples from above.
As you can see, RunJS makes it extremely easy to write and run code.
Conclusion
Running a Node.js server locally is a straightforward process. Whether you're using plain Node.js or Express, these steps will get your local server up and running in no time. Remember to stop the server using Ctrl + C
when you're done. Happy coding!