In a previous post we used webpack to run an HTTP server, in this post we’re going to create a bare bones HTTP server using the http package.
In your chosen folder run the usual commands
- yarn init y
- tsc –init
- Add a folder named public off of the folder you source will be in (this will be where we add static html files)
Now lets’ add the required packages
- yarn add node-static @types/node-static
Add the following to the package.json
"scripts": { "start": "node server.js", "build": "tsc" }
In the public folder add index.html with the following
<html> <head></head> <body> Hello World </body> </html>
Now let’s add the code to start up our server (mine’s in the file server.ts)
import ns from "node-static"; import http from "http" const file = new ns.Server("./public"); http.createServer((request, response) => { request.addListener("end", () => { file.serve(request, response); }) .resume() }) .listen(4000);
Simple run yarn build then yarn start and the server will start. Navigating your preferred browser to http://localhost:4000/ will then display the HTML file, i.e. Hello World text.