Setting up node JS

Install node from the website

In VS code, open new project folder, and in the terminal type

$npm init
This will create package.json

$npm install express
Automatically adds express to the package.json file, and creates the node modules folder in the project folder

Now create two files,
index.js (this will be our node server)
index.html (our page to serve from node server)

In index.js, add the following code

const express = require("express");
const app = express();

app.listen(3000, () => console.log("Listening on port 3000"));

Here we import express, and we assign the express function to the variable app.

We then get express to listen on port 3000.

Now in the $bash console, type

$node index.js

.. and now our server is running.

If we now go to localhost:3000 in the browser we see this

… there’s nothing there, there’s nothing to get! Our server has nothing on it.

So let’s get our server to serve our first page, which will be index.html

Above, we tell node that we have a folder called public and in that folder will be all the pages that are publicly accessible from our server.

So on our project, create a folder called public and put our index.html file in there.

Note: too see the changes on the server, in the bash terminal, we need to CTRL+C to turn off the server, then type node index.js again to restart it. So every time we make changes to the server code (index.js) we need to stop and restart the server for the changes to take effect. To avoid having to do this we can use ‘node monitor’

We can install nodemon as a global module by typing
npm install -g nodemon
in the bash console. Now we can type $ nodemon index.js to use it and we then don’t keep having to stop and start the server when we make code changes to it.

Sometimes using nodemon we’ll find it referring to a previous server, we need to clear the cache using

$ npm cache clean –force

Now if we go to localhost:3000 we will see nothing, because there’s nothing in index.html right now.

Now we see

How to post data using fetch to nodeJS

index.js (the server)


Leave a Reply