In this quick-tip article we’ll see how to set up a brand new Express app and serve it with Node.

A villa with a pool Screenshot by codingexercises

How to add Express to a brand new npm project?

First, we’ll need to make a new folder, and give it a name.

Let’s say we’ll call it: simpleExpress.

Next, we’ll open a console program and run this command:

npm init -y

The -y is the “default” flag, meaning, we’re avoiding npm prompts by accepting all the default values.

This creates a package.json file in our new folder. The package.json file will list all the dependencies our project will use.

Next, we’ll install Express.

Installing Express as our project’s dependency

Now to install express we run this command:

npm install --save express

We are using the --save flag so that npm saves Express as our project’s dependency inside package.json file.

Now we have saved Express, let’s add a new file from the console, by running:

code . index.js

The above command will only work if you have VS Code installed!

Writing a minimal Express app

Inside the new index.js file, type the following script:

1
2
3
4
5
6
7
8
var express = require('express');
var app = express();

app.get('/', function (req, res) {
    res.send('Hello Express!');
});

app.listen(3000);

Now, let’s run the Node server to serve index.js:

node index.js

That’s it, visit localhost: 3000 in your browser, and you’ll see the output: Hello Express!.