Running a Node.js server is a straightforward process. Here are the steps you can follow:
Step 1: Install Node.js
If you don’t have Node.js installed, you’ll need to install it first.
- Visit the Node.js download page.
- Download and install the latest stable version of Node.js for your operating system.
Step 2: Create a Simple Node.js Server
- Create a new directory for your project (e.g.,
my-node-server
):mkdir my-node-server cd my-node-server
- Initialize a new Node.js project:
npm init -y
This will create a
package.json
file. - Create a new JavaScript file (e.g.,
server.js
) and add the following code:const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, Node.js server!\n'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
Step 3: Run the Server
In the terminal, run the following command to start the server:
node server.js
Step 4: Access the Server
Once the server is running, open your browser and visit:
http://127.0.0.1:3000
You should see the message “Hello, Node.js server!”.
Additional Notes:
- If you’re using a framework like Express.js, you can set up a more complex server with routes and middleware.
- You can stop the server at any time by pressing
Ctrl+C
in the terminal.
That’s it! You’ve successfully set up and run a simple Node.js server.