Setting up an efficient, scalable, and productive Node.js development environment is essential for developing modern applications. This guide walks through a comprehensive setup to streamline development, enforce code quality, use environment configuration, and utilize modern tools and libraries that improve workflow, debugging, and performance.
mkdir advanced-node-app
cd advanced-node-app
npm init -y
This creates a package.json file with default values and initializes your Node.js project.
npm install express dotenv mongoose cors
Nodemon automatically restarts the server when file changes are detected.
npm install --save-dev nodemon
Add the following script to your package.json:
"scripts": {
"start": "node app.js",
"dev": "nodemon app.js"
}
npm install --save-dev eslint
npx eslint --init
Choose a style guide like Airbnb or Standard, and set it up with your preferred module system (CommonJS or ESModules).
npm install --save-dev prettier
Create a file .prettierrc:
{
"semi": true,
"singleQuote": true,
"printWidth": 80
}
npx husky-init && npm install
npm install --save-dev lint-staged
Update package.json with:
"lint-staged": {
"*.js": [
"eslint --fix",
"prettier --write"
]
}
Maintain a clean and modular folder layout:
advanced-node-app/
βββ config/
β βββ database.js
βββ controllers/
βββ middlewares/
βββ models/
βββ routes/
βββ utils/
βββ app.js
βββ .env
PORT=5000
MONGO_URI=mongodb://localhost:27017/advanced_db
JWT_SECRET=supersecret
require('dotenv').config();
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('MongoDB connected');
} catch (err) {
console.error('MongoDB connection failed:', err.message);
process.exit(1);
}
};
module.exports = connectDB;
npm install morgan
const morgan = require('morgan');
app.use(morgan('dev'));
npm install debug
const debug = require('debug')('app:startup');
debug('Debugging is enabled');
Enable debug logs via:
DEBUG=app:* npm run dev
Structure your routes like:
routes/
βββ v1/
βββ users.js
const errorHandler = (err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: err.message });
};
module.exports = errorHandler;
npm install helmet
const helmet = require('helmet');
app.use(helmet());
npm install express-rate-limit
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
});
app.use(limiter);
npm install express-mongo-sanitize
const mongoSanitize = require('express-mongo-sanitize');
app.use(mongoSanitize());
Create and share Postman collections with:
npm install --save-dev jest supertest
const request = require('supertest');
const app = require('../app');
describe('GET /', () => {
it('should return 200 OK', async () => {
const res = await request(app).get('/');
expect(res.statusCode).toBe(200);
});
});
FROM node:18
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 5000
CMD [ "npm", "start" ]
node_modules
.env
By setting up a well-organized, tool-rich Node.js development environment, you can ensure better productivity, maintainability, and scalability of your projects. Whether you're building a REST API, microservices, or full-stack applications, this environment provides everything needed to write clean, consistent, and secure code.
A function passed as an argument and executed later.
Runs multiple instances to utilize multi-core systems.
Reusable blocks of code, exported and imported using require() or import.
nextTick() executes before setImmediate() in the event loop.
Starts a server and listens on specified port.
Node Package Manager β installs, manages, and shares JavaScript packages.
A minimal and flexible web application framework for Node.js.
A stream handles reading or writing data continuously.
It processes asynchronous callbacks and non-blocking I/O operations efficiently.
Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.
An object representing the eventual completion or failure of an asynchronous operation.
require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).
Use module.exports or exports.functionName.
Variables stored outside the code for configuration, accessed using process.env.
MongoDB, often used with Mongoose for schema management.
Describes project details and manages dependencies and scripts.
Synchronous blocks execution; asynchronous runs in background without blocking.
Allows or restricts resources shared between different origins.
Use try-catch, error events, or middleware for error handling.
Provides file system-related operations like read, write, delete.
Using event-driven architecture and non-blocking I/O.
Functions in Express that execute during request-response cycle.
A set of routes or endpoints to interact with server logic or databases.
Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.
Middleware to parse incoming request bodies, like JSON or form data.
Copyrights © 2024 letsupdateskills All rights reserved