ExoSnip Code Snippets

Node.js Snippets

← Back to Home

About Node.js

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows you to run JavaScript on the server-side. This guide walks you through creating a simple web server in Node.js with best practices for project structure.

Project Directory Structure

Step 1: A well-organized project structure helps maintain clean and scalable code. Here’s the recommended file structure for your Node.js project:

  • node-app/: Root directory of the project.
  • src/: Contains source code.
    • routes/: Contains route handlers.
      • index.js: Main route handler.
    • controllers/: Contains controller functions.
      • homeController.js: Controller for home route.
    • app.js: Main application file.
  • package.json: Contains project metadata and dependencies.
  • README.md: Project documentation.

node-app/
│── src/
│   ├── routes/
│   │   ├── index.js
│   ├── controllers/
│   │   ├── homeController.js
│   ├── app.js
│── package.json
│── README.md

Install Node.js and Initialize Project

Step 2: Before starting, you need to install Node.js. After installing Node.js, you can initialize a new Node.js project using npm (Node Package Manager). This will create a `package.json` file to manage your project's dependencies.

npm init -y

Create a Simple Web Server (app.js)

Step 3: In this step, you will create a simple web server using Node.js. This server will listen on a specified port and respond with 'Hello, World!' when accessed.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Create Route Handlers (index.js)

Step 4: In this step, you will create route handlers to manage different routes in your application. This example shows how to handle the root route ('/').

const express = require('express');
const router = express.Router();
const homeController = require('../controllers/homeController');

router.get('/', homeController.home);

module.exports = router;

Create Controller Functions (homeController.js)

Step 5: Here, you will create a controller function to handle the logic for the home route. This function will send a response with 'Welcome to Node.js!' when the root route is accessed.

exports.home = (req, res) => {
  res.send('Welcome to Node.js!');
};

Integrate Routes in Main Application (app.js)

Step 6: In this step, you will integrate the route handlers into the main application file. This will allow your application to handle different routes using the route handlers you created.

const express = require('express');
const app = express();
const indexRouter = require('./routes/index');

app.use('/', indexRouter);

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

Install Express.js

Step 7: Express.js is a web application framework for Node.js. It provides a robust set of features to develop web and mobile applications. You need to install Express.js to handle routing and middleware in your Node.js application.

npm install express

Run the Node.js Application

Step 8: Now that your Node.js application is complete, you can start the server to see your app in action. This will allow you to interact with your Node.js application in a web browser.

node src/app.js

Best Practices for Project Structure

Step 9: Follow these best practices to keep your project clean and maintainable: 1. Use a routes folder: Keep route handlers in `src/routes/` for better organization. 2. Separate logic from routes: Maintain controller functions in `src/controllers/` while keeping route definitions in separate files. 3. Use meaningful file names: Avoid generic names like `handler.js`, use `homeController.js`, `index.js`, etc. 4. Keep functions reusable: Functions like `home` should be kept modular for reusability. 5. Keep configuration separate: Use environment variables or configuration files for settings like port numbers.

1. Use a routes folder: Keep route handlers in `src/routes/` for better organization.
2. Separate logic from routes: Maintain controller functions in `src/controllers/` while keeping route definitions in separate files.
3. Use meaningful file names: Avoid generic names like `handler.js`, use `homeController.js`, `index.js`, etc.
4. Keep functions reusable: Functions like `home` should be kept modular for reusability.
5. Keep configuration separate: Use environment variables or configuration files for settings like port numbers.