Setup a Nodejs project using Express as the framework

Hi, Welcome to the first blog of the series where we will learn how to setup a Node project with Express and MongoDB using Typescript as the programming language.

As a newbie programmer I always found it difficult to follow best way to write code and structure the project. Here I will try my best to demonstrate what I learnt through my developer carrier. Any suggestions/corrections are welcome.

Here I'm using typescript as programming language because it simplifies Javascript and makes the code easier to read and debug. (Find more about Typescript in this article)

Setting up the application

Open terminal and move to desktop or any folder where you want to create the application. Here I want to create my project in Desktop so,

cd Desktop

And then create folder named node_ts

mkdir node_ts

By now, on your desktop, a folder named node_ts will be created. Now open any code editor of your choice but I prefer Visual Studio Code. If you don't have it, you can download it from here Download

Open node_ts folder that you created earlier in the editor and now open terminal in VS code from terminal option at the top or by clicking Ctrl+` image.png

Now type the below and hit enter in the terminal opened.

npm init -y

After this there a file named package.json will be created in the folder. And now we need to install dependencies and that information will be stored in this file. Type npm install express and hit enter to install express framework in our project

npm install express

And now you will see node_modules folder and package-lock.json files get created in the folder. And in package.json file, under dependencies you will see express and version next to it. image.png We will talk about this in detail in future section.

To use TypeScript, you also need to install a stable version of typescript as a developer dependency (i as short hand for install and -D indicates, this is a dev-dependancy)

npm i -D typescript

To use TypeScript effectively, you need to install type definitions for the packages you installed.

npm i -D @types/node @types/express

Initialize TypeScript in Node.js

To help the TypeScript compiler understand your project's structure, you need to create a tsconfig.json file within the directory you want to use as the root directory of the TypeScript project. In this case, your project directory and the TypeScript project directory are the same.

To easily generate the tsconfig.json file, ensure that you are under the project directory and issue the following command:

npx tsc --init

That's all that you need for now to configure your TypeScript project with sensible defaults.

Now create an Express app with Typescript

To keep your application well-organized, create an src directory to host your Node.js application files. And under src folder create a file named index.ts to serve as entry point for application.

mkdir src
touch src/index.ts

And now add below code to index.ts file which you just created

import express, {Request, Response} from "express";
import { Server } from "http";

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true })); 

app.get('/', (req: Request, res: Response) => {
  res.send("Hi, Welcome to my nodejs app!");
});

const port = 3000;

const server: Server = app.listen({ port }, () => {
  console.log(`Server ready at http://localhost:${port}`);
});

Improve TypeScript Development Workflow

The TypeScript compilation process can increase the bootstrapping time of an application. However, you don't need to recompile the entire project whenever there's a change in its source code. You can set up ts-node-dev to significantly decrease the time it takes to restart your application when you make a change.

Start by installing this package to power up your development workflow:

npm i -D ts-node-dev

ts-node-dev restarts a target Node.js process when any of the required files change. However, it shares the Typescript compilation process between restarts, which can significantly increase the restart speed.

You can create a dev npm script in package.json to run your server: Add "dev": "ts-node-dev --respawn --pretty --transpile-only src/index.ts" to the scripts in package.json file

image.png

Let's briefly break down the options that ts-node-dev takes:

--respawn: Keep watching for changes after the script has exited.

--pretty: Use pretty diagnostic formatter (TS_NODE_PRETTY).

--transpile-only: Use TypeScript's faster transpileModule (TS_NODE_TRANSPILE_ONLY).

src/index.ts: This is the application's entry file.

Since ts-node-dev is a tweaked version of node-dev that uses ts-node under the hood, some of its options are the combined options of those two packages. Refer to its "Usage Document" for more details and available options.

Now, simply run the dev script to launch your project:

npm run dev

If everything is working correctly, you will see a log Server ready at localhost:3000 in the terminal. Now your Node.js app is ready and you can test by searching for url http:localhost:3000 in your browser and you will see Hi, Welcome to my nodejs app! on the browser. image.png

Congratulations! You have just created a Node.js app successfully!

This is my first blog, so apologies in case of any mistakes done. In case of any queries or corrections, please let me know in the comment section. You can download th code from my github.