In this lab, you will learn how to:
- Set up a Node.js project using TypeScript with CommonJS module syntax.
- Configure TypeScript compiler (tsc) properly.
- Run your TypeScript code directly using ts-node or nodemon.
- Create one working API route
POST /booksto add a book to a JSON file. - Test it manually using Postman or
curl.
This lab will teach you the foundation for writing backend APIs in TypeScript — without using import/export syntax.
mkdir ts-node
cd ts-node
npm init -ynpm install express
npm install --save-dev typescript ts-node @types/node @types/express nodemonnpx tsc --init{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"rootDir": "./src",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}ts-node-commonjs-lab/
│
├── package.json
├── tsconfig.json
├── src/
│ ├── server.ts
│ ├── routes/
│ │ └── bookRoutes.ts
│ ├── controllers/
│ │ └── bookController.ts
│ └── data/
│ └── books.json
└── dist/ (will be generated after build)import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
// Recreate __dirname and __filename for ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Path to JSON file
const dataFile = path.join(__dirname, '../data/books.json');"types": ["node", "express"](req: any, res: any);"scripts": {
"dev": "nodemon --watch src --exec \"node --loader ts-node/esm --experimental-specifier-resolution=node\" src/server.ts",
"build": "tsc",
"start": "node dist/server.js"
}npm run devUsing curl
curl -X POST http://localhost:3000/books \
-H "Content-Type: application/json" \
-d '{"title":"Atomic Habits","author":"James Clear","year":2018}'