How to make a static http server in nodejs using express


Express is a fast unopinionated, minimalist web framework for nodejs
Authored by  TJ Holowaychuk
Express is a framework for building robust http servers, single page applications and API's among others.

How to create an http server in express

Open your text editor and terminal,
run the commands below to create a project directory, application file
and a landing page

mkdir project
cd project
mkdir static
echo "Hello World" > static index.html
touch app.js

You must have a directory structure as follows;
|Project/
    |static/
        |index.html
    |app.js

Project directory is the root directory of the application
Static directory is where static files, webpages will be stored.

index.html is an index page with text "Hello world".

app.js is a blank JavaScript file, open your editor and paste the following few lines of code into app.js


import express from 'express'
const app = express()
const port = 3000
app.use('/', express.static('static'))
app.listen(port, () => console.log(`Express Server Listening on localhost:${port}`))


Save the file and open your terminal, in the project directory type;
node app.js

In the code above express module is imported on the upper most line of code.

Second line an instance of express is created assigned to the variable app
the port variable is declared assigned to 3000

On the following line express i directed to make static files available or "resolve" on the root path
The final line of code instructs express to listen on the specified port.

Upon running the file you'll get notified that the http server is running on port 3000 as set earlier.

Comments

  1. You can put html documents 'webpages' in the static directory to create a simple website

    or serve mp3 files and make a media server

    ReplyDelete

Post a Comment

Popular posts from this blog

Snake monochrome (JS1024)

What is 'this.' keyword in JavaScript

Open-graph meta data tags introdution

what is 'array.includes' function in JavaScript

How to create zip archives in nodejs