Crate a Simple NodeJS Server


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.

  1. Set Up Your Project
  2. 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
      
    
    
  3. Create the Server
  4. 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}`)
      })
    
    
  5. Run the Server
  6. 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!

<< Back