HomeContact
NodeJS
Create a Node.js server and start or stop it from the command line.
March 27, 2020
1 min

This article will show you how to quickly install and create a Node.js server.

First you’ll need to install Node.js on your computer : You can go to the official Node.js link and download the installer

  • Or if you have a mac you can use Brew (a Mac package manager) if installed : brew install node

  • For windows if you use Chocolatey you can simply : choco install nodejs

  • Or linux user : sudo apt-get install -y nodejs

During the installation, create a file called hello-world.js and file it with :

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, World!\n')
})

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`)
})

Then when the installation of Node.js is done, type in your command line interface node hello-world.js

You should see a message telling you that the server started :

Server running at http://127.0.0.1:3000/

Visit the url and voilà ! You should see the message ‘Hello World !‘.

To kill it simply use Ctrl+C keyboard shortcut, it will kill the process.

However, using Ctrl-Z will suspend the process but not kill it. The server will still run on the PORT, if you go to the page you will not see an error from your browser but a blank page, meaning that the process return nothing. If you try again to restart the server with node hello-world.js it will throw you an error telling you that the PORT is already used. Close your command line then to effectively kill it.


Tags

javascriptnodejs

Related Posts

How to call a route internally using NodeJS
April 11, 2022
1 min
© 2023, All Rights Reserved.

Quick Links

Contact Us

Social Media