Restu Oktafiandi
Published Blog · 1 min read · October 2, 2024
In this quick tutorial, you'll learn how to create a basic server using Node.js.
First, create a new folder for your project and navigate into it:
mkdir node-server
cd node-server
Then, initialize the project with npm:
npm init -y
Create a new file called server.js:
touch server.js
Inside this file, add the following code:
import { createServer } from 'node:http'
const hostname = '127.0.0.1'
const port = 3000
const server = createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello World')
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}`)
})
To start the server, run this command:
node server.js
Open your browser and go to http://127.0.0.1:3000
, and you should see the message "Hello,
World!".
You’ve successfully created a simple Node.js server. Enjoy coding!