Intro to nodeJS

Intro to NodeJS

NPM

Running Your Node.js App Locally

Set Up Your Files

Create a folder called my-app and put your files in it like this:

my-app/
  server.js
  public/
    index.html
    main.js
    main.css

The public/ folder holds everything the browser sees. server.js sits outside it.


Run the Server!

Open your terminal, navigate to your project folder, and start the server:

cd my-app
node server.js

You should see:

Server running at http://localhost:3000

Open your browser and go to http://localhost:3000.

To stop the server, press Ctrl+C in the terminal.

Express

What does Express do for us? Why are we using it?

Let’s visit the website for Express.

It explains that Express is a fast, unopionated minimalist web framework. Fast is obvious. Unopinionated is coder-speak for: “you can write code any which way you please. There isn’t a single way you have to write it if you use our library with it.” Okay, but what is a web framework?

Express provides a simple way (a mini “language”) to serve pages. It is like a switchboard operator that receives a call (“Hello, I’d like to speak to lee in Henley-4562”). What are we routing? When a user requests a particular webpage, that gets routed via our code, and specific content (“a view”) is served.

How does this work? Express looks for the route specified in the URL bar.

MyWebsite.com/theRouteIamRequesting

the Route looks like a sub-folder, but it’s actually a bit of information that is communicated. Express takes this info, and then figures out what to display.

var express = require(‘express’);

//you can now create an ‘app’ //This app holds an instance of express and can use its functionality

var app = express();

var server = app.listen(4000); //listens on port 4000. Triggers callback.

app.use(express.static(‘public’)); ```

This means http://localhost:4000 will host the project

## Running Your Node.js App Locally with Express

### Step 1 — Set Up Your Files

Create a folder called `my-app` and put your files in it like this:

my-app/ server.js public/ index.html main.js main.css


The `public/` folder holds everything the browser sees. `server.js` sits outside it.

---

## Step 2 — Install Express

Open your terminal, navigate to your project folder, and run:

```bash
cd my-app
npm init -y
npm install express

npm init -y creates a package.json file for your project. npm install express downloads Express into a node_modules/ folder.


Step 3 — Run the Server

node server.js

You should see:

Server running at http://localhost:3000

Open your browser and go to http://localhost:3000.

To stop the server, press Ctrl+C in the terminal.