The following example uses Express to create an HTTP server listening on port 3000, which responds with "Hello, World!". Express is a commonly-used web framework that is useful for creating HTTP APIs.
First, create a new folder, e.g. myApp
. Go into myApp
and make a new JavaScript file containing the following code (let's name it hello.js
for example). Then install the express module using npm install --save express
from the command line. Refer to this documentation for more information on how to install packages.
// Import the top-level function of express
const express = require('express');
// Creates an Express application using the top-level function
const app = express();
// Define port number as 3000
const port = 3000;
// Routes HTTP GET requests to the specified path "/" with the specified callback function
app.get('/', function(request, response) {
response.send('Hello, World!');
});
// Make the app listen on port 3000
app.listen(port, function() {
console.log('Server listening on http://localhost:' + port);
});
From the command line, run the following command:
node hello.js
Open your browser and navigate to http://localhost:3000
or http://127.0.0.1:3000
to see the response.
For more information about the Express framework, you can check the Web Apps With Express section