How To Get Started with Node JS and Express

How To Get Started with Node JS and Express

Express is a web application framework for Node JS that allows you to spin up robust APIs and web servers in a much easier and cleaner way. It is a lightweight package that does not obscure the core Node JS features.

Step 1 — Setting Up the Project

First, open your terminal window and create a new project directory:

mkdir express-example

cd express-example

At this point, you can initialise a new npm project:

npm init -y

Next, you will need to install the express package:

npm install [email protected]

At this point, you have a new project ready to use Express.

Step 2 — Creating an Express Server

Now that Express is installed, create a new server.js file and open it with your code editor. Then, add the following lines of code:

server.js

const express = require('express');

const app = express();/

The first line here is grabbing the main Express module from the package you installed. This module is a function, which we then run on the second line to create our app variable. You can create multiple apps this way, each with its own requests and responses.

server.js

const express = require('express');

const app = express();

app.get('/', (req, res) => {

res.send('Successful response.');

});

These lines of code is where we tell our Express server how to handle a GET request to our server. Express includes similar functions for POST, PUT, etc. using app.post(...), app.put(...), etc.

The second parameter is a function with two arguments: req, and res. req represents the request that was sent to the server; We can use this object to read data about what the client is requesting to do. res represents the response that we will send back to the client.

Here, we are calling a function on res to send back a response: 'Successful response.'.

server.js

const express = require('express');

const app = express();

app.get('/', (req, res) => {

res.send('Successful response.');

});

app.listen(3000, () => console.log('Example app is listening on port 3000.'));

Finally, once we’ve set up our requests, we must start our server! We are passing 3000 into the listen function, which tells the app which port to listen on. The function passed in as the second parameter is optional and runs when the server starts up. This provides us some feedback in the console to know that our application is running.

Revisit your terminal window and run your application:

node server.js

Then, visit localhost:3000 in your web browser. Your browser window will display: 'Successful response'. Your terminal window will display: 'Example app is listening on port 3000.'.

And there we have it, a web server! However, we definitely want to send more than just a single line of text back to the client. Let’s briefly cover what middleware is and how to set this server up as a static file server!

Step 3 — Using Middleware

With Express, we can write and use middleware functions, which have access to all HTTP requests coming to the server. These functions can:

. Execute any code.

. Make changes to the request and the response objects.

. End the request-response cycle.

. Call the next middleware function in the stack.

We can write our own middleware functions or use third-party middleware by importing them the same way we would with any other package.

Let’s start by writing our own middleware, then we’ll try using some existing middleware to serve static files.

To define a middleware function, we call app.use() and pass it a function. Here’s a basic middleware function to print the current time in the console during every request:

server.js

const express = require('express');

const app = express();

app.use((req, res, next) => {

console.log('Time: ', Date.now());

next();

});

app.get('/', (req, res) => {

res.send('Successful response.');

});

app.listen(3000, () => console.log('Example app is listening on port 3000.'));

The next() call tells the middleware to go to the next middleware function if there is one. This is important to include at the end of our function - otherwise, the request will get stuck on this middleware.

We can optionally pass a path to the middleware, which will only handle requests to that route. For example:

server.js

const express = require('express');

const app = express();

app.use((req, res, next) => {

console.log('Time: ', Date.now());

next();

});

app.use('/request-type', (req, res, next) => {

console.log('Request type: ', req.method);

next();

});

app.get('/', (req, res) => {

res.send('Successful response.');

});

app.listen(3000, () => console.log('Example app is listening on port 3000.'));

By passing '/request-type' as the first argument to app.use(), this function will only run for requests sent to localhost:3000/request-type.

Revisit your terminal window and run your application:

node server.js

Then, visit localhost:3000/request-type in your web browser. Your terminal window will display the timestamp of the request and 'Request type: GET'.

Now, let’s try using existing middleware to serve static files. Express comes with a built-in middleware function: express.static. We will also use a third-party middleware function, serve-index, to display an index listing of our files.

First, inside the same folder where the express server is located, create a directory named public and put some files in there.

Then, install the package serve-index:

npm install [email protected]

First, import the serve-index package at the top of the server file.

Then, include the express.static and serveIndex middlewares and tell them the path to access from and the name of the directory:

server.js

const express = require('express');

const serveIndex = require('serve-index');

const app = express();

app.use((req, res, next) => {

console.log('Time: ', Date.now());

next();

});

app.use('/request-type', (req, res, next) => {

console.log('Request type: ', req.method);

next();

});

app.use('/public', express.static('public'));

app.use('/public', serveIndex('public'));

app.get('/', (req, res) => {

res.send('Successful response.');

});

app.listen(3000, () => console.log('Example app is listening on port 3000.'));

Now, restart your server and navigate to localhost:3000/public. You will be presented with a listing of all your files!

Explain the concept of streams in Node.js. How are they used, and what are …

In Node.js, streams are powerful mechanisms for handling data transfer, especially when dealing with large amounts of data or performing I/O operations. Streams provide an abstraction for handling data in chunks, rather than loading entire datasets i …

read more

How To Work With Zip Files in Node.js

Working with zip files in Node.js involves using third-party libraries as Node.js doesn't provide built-in support for zip file manipulation. One of the popular libraries for handling zip files in Node.js is adm-zip. Below are the steps to work with …

read more