Initial Version
Create a package
Run the npm init
command to create a package.json file for your application.
npm init
This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them except the entry point.
We prefer to use app.js rather than index.js.
Its result should be similar to this:
package name: (lr_rest_books_node)
version: (1.0.0)
description: RESTful API implemented with Express in Node.js.
entry point: (index.js) app.js
test command:
git repository: https://github.com/Literank/lr_rest_books_node.git
keywords: express,rest,books
author: literank.com
license: (ISC) MIT
{
"name": "lr_rest_books_node",
"version": "1.0.0",
"description": "RESTful API implemented with Express in Node.js.",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Literank/lr_rest_books_node.git"
},
"keywords": [
"express",
"rest",
"books"
],
"author": "literank.com",
"license": "MIT",
"bugs": {
"url": "https://github.com/Literank/lr_rest_books_node/issues"
},
"homepage": "https://github.com/Literank/lr_rest_books_node#readme"
}
This command creates a package.json
file in which dependencies you add will be listed for tracking.
Install Express
npm install express
This command updates the package.json
file and creates a package-lock.json
file in your project.
Create app.js:
const express = require("express");
const app = express();
const port = 3000;
app.get("/ping", (req, res) => {
res.send({ message: "pong" });
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
Run the program like this:
node app.js
You will get one line like this:
Listening on port 3000
Your API server is running on port 3000 now.
Try to hit the endpoint /ping
with curl
command:
curl http://localhost:3000/ping
It shows:
{"message":"pong"}
Nice! Your server is doing well.
Transform to TypeScript
Using TypeScript in a Node.js project offers several benefits:
- Static Typing: TypeScript allows you to define types for variables, parameters, and return values. This helps catch type-related errors during development rather than at runtime, leading to more robust and predictable code.
- Improved Code Readability: With type annotations, code becomes more self-documenting, making it easier for developers to understand the codebase and collaborate effectively. Type information serves as additional documentation, especially for large projects.
- Enhanced IDE Support: TypeScript provides better tooling support in IDEs like Visual Studio Code, offering features such as code navigation, auto-completion, and inline documentation, which can improve productivity and code quality.
So, let's transform it.
Run the following command to install typescript dependencies:
npm install typescript ts-node @types/node @types/express --save-dev
The --save-dev
flag ensures that these dependencies are saved as devDependencies, as they are only required during the development process.
Create tsconfig.json in your root directory:
{
"compilerOptions": {
"target": "ESNext",
"module": "CommonJS",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
Move app.js to src/app.ts and update its content:
import express, { Request, Response } from "express";
const app = express();
const port = process.env.PORT || 3000;
app.get("/ping", (req: Request, res: Response) => {
res.json({ message: "pong" });
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
Add scripts to package.json:
@@ -4,7 +4,9 @@
"description": "RESTful API implemented with Express in Node.js.",
"main": "app.js",
"scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
+ "dev": "ts-node src/app.ts",
+ "build": "tsc",
+ "serve": "node dist/app.js"
},
"repository": {
Run the new program like this:
npm run dev
Try to hit the endpoint /ping
with curl
command again:
curl http://localhost:3000/ping
It still shows:
{"message":"pong"}
Nice! Your TypeScript version API is doing fine.