Project Structure
A standard Node.js project includes several key files:- LICENSE: The license file detailing usage rights.
- README: Documentation and usage instructions.
- package.json: Contains application metadata and dependencies.
- app.js: The entry point of the application.
- public: Contains front-end assets like HTML, CSS, and JavaScript.
- test: Directory for automated tests.
- config: Configuration files.
- routes: API route definitions.
- services: External service implementations.
- DB: Database models and seed files.
- core: Core business logic.
Application Code (app.js)
Theapp.js file demonstrates a basic Express application. It serves static files from the public directory and provides an API endpoint to retrieve a list of products. The application listens on port 3000.
Installing Dependencies
After downloading the source code, install the necessary dependencies by running the following command in the terminal:Running the Application
Development and Production Modes
Once the dependencies are installed, start the application using Node.js. Since the entry point isapp.js, you can launch it directly:
NODE_ENV variable.
Using environment-specific scripts ensures that your application remains consistent across different stages, such as development, testing, and production.
Production Process Management
While running an application withnode app.js or via npm scripts can work well during development, they are not reliable for production environments. A crash in Node.js will terminate the process, potentially causing downtime. To avoid this, it is best to use a production-grade process manager.
Using PM2 for Production
PM2 is a robust process manager that comes with a built-in load balancer. To start your application with PM2, simply run:Avoid running production applications directly with Node.js commands, as this can lead to uptime issues if the application crashes. Use a process manager like PM2 for enhanced reliability.
Summary
This lesson provided an overview of deploying an Express.js application, covering:- A typical Node.js project structure.
- Setting up and configuring the
app.jsfile. - Installing dependencies with npm.
- Managing different environments using npm scripts.
- Deploying the application with a process manager like PM2 for production.