|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1. Node.js简介及其优势
Node.js是一个基于Chrome V8引擎的JavaScript运行时环境,它允许JavaScript在服务器端运行。Node.js使用事件驱动、非阻塞I/O模型,使其轻量且高效,特别适合构建数据密集型的实时应用。
Node.js的主要优势:
• 高性能:基于V8引擎,执行速度快
• 非阻塞I/O:采用事件循环机制,能处理大量并发连接
• 前后端语言统一:使用JavaScript,减少学习成本
• 丰富的生态系统:npm(Node包管理器)拥有大量开源包
• 跨平台:支持Windows、Linux、Mac OS等多种操作系统
2. 环境准备
在开始Node.js项目之前,我们需要先安装Node.js和npm(Node包管理器)。
安装Node.js和npm
1. 访问Node.js官网(https://nodejs.org/)
2. 下载LTS(长期支持)版本,推荐大多数用户使用
3. 根据操作系统提示完成安装
安装完成后,打开终端(Windows用户可以使用命令提示符或PowerShell),运行以下命令验证安装:
如果安装成功,你将看到类似以下的输出:
使用nvm管理Node.js版本(可选)
如果你需要在不同项目中使用不同版本的Node.js,推荐使用nvm(Node Version Manager)来管理Node.js版本。
- curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
复制代码
1. 访问nvm-windows的GitHub页面(https://github.com/coreybutler/nvm-windows)
2. 下载最新版本的nvm-setup.zip
3. 解压并运行nvm-setup.exe
安装完成后,可以使用以下命令安装和切换Node.js版本:
- # 安装特定版本的Node.js
- nvm install 16.14.0
- # 切换到指定版本
- nvm use 16.14.0
- # 查看已安装的版本
- nvm ls
- # 查看可用的远程版本
- nvm ls-remote
复制代码
3. 项目初始化
创建项目目录
首先,我们需要为项目创建一个目录:
- mkdir my-node-project
- cd my-node-project
复制代码
使用npm init初始化项目
在项目目录中,运行以下命令来初始化项目:
这将启动一个交互式命令行界面,引导你设置项目的基本信息,如项目名称、版本、描述、入口文件、测试命令、Git仓库、关键词、作者和许可证等。
如果你想跳过交互式界面并使用默认设置,可以使用以下命令:
package.json文件详解
初始化完成后,项目目录中会生成一个package.json文件,这是Node.js项目的核心配置文件。一个典型的package.json文件如下:
- {
- "name": "my-node-project",
- "version": "1.0.0",
- "description": "A sample Node.js project",
- "main": "index.js",
- "scripts": {
- "test": "echo "Error: no test specified" && exit 1"
- },
- "keywords": [
- "node",
- "project"
- ],
- "author": "Your Name",
- "license": "ISC"
- }
复制代码
package.json文件的主要字段说明:
• name:项目名称,必须是小写字母,可以包含连字符和下划线
• version:项目版本,遵循语义化版本控制(semver)规范
• description:项目描述
• main:项目入口文件
• scripts:定义可执行的脚本命令
• keywords:项目关键词,有助于其他人在npm上发现你的项目
• author:作者信息
• license:项目许可证
• dependencies:生产环境依赖
• devDependencies:开发环境依赖
4. 依赖管理
安装依赖
在Node.js项目中,我们可以使用npm来安装和管理依赖。
- npm install express mongoose body-parser
复制代码
生产依赖与开发依赖
这些是项目运行时需要的依赖,使用--save或-S标志安装(默认行为):
- npm install express --save
- # 或
- npm install express -S
复制代码
这些是开发过程中需要的依赖,如测试工具、代码格式化工具等,使用--save-dev或-D标志安装:
- npm install eslint --save-dev
- # 或
- npm install eslint -D
复制代码
版本控制
npm使用语义化版本控制(semver)来管理依赖版本。版本号格式为:主版本号.次版本号.修订号(MAJOR.MINOR.PATCH)。
• 主版本号:当做了不兼容的API修改
• 次版本号:当做了向下兼容的功能性新增
• 修订号:当做了向下兼容的问题修正
在package.json中,可以使用以下符号来指定版本范围:
• 精确版本:"express": "4.17.1"- 只安装4.17.1版本
• 波浪号:"express": "~4.17.1"- 安装4.17.x版本,但不包括4.18.0
• 插入符号:"express": "^4.17.1"- 安装4.x.x版本,但不包括5.0.0
• 大于/小于:"express": ">4.17.0"- 安装大于4.17.0的版本
• 任意版本:"express": "*"- 安装最新版本
全局安装依赖
有些工具(如nodemon、create-react-app等)需要全局安装:
卸载依赖
更新依赖
- # 检查过时的依赖
- npm outdated
- # 更新单个依赖
- npm update express
- # 更新所有依赖
- npm update
复制代码
常用依赖介绍
Express.js是最流行的Node.js Web应用框架,提供了一系列强大的功能来开发Web和移动应用。
示例代码:
- const express = require('express');
- const app = express();
- const port = 3000;
- app.get('/', (req, res) => {
- res.send('Hello World!');
- });
- app.listen(port, () => {
- console.log(`Example app listening at http://localhost:${port}`);
- });
复制代码
Mongoose是MongoDB的对象建模工具,专为异步环境设计。
示例代码:
- const mongoose = require('mongoose');
- // 连接到MongoDB
- mongoose.connect('mongodb://localhost:27017/my_database', {
- useNewUrlParser: true,
- useUnifiedTopology: true
- });
- // 定义模式
- const userSchema = new mongoose.Schema({
- name: String,
- email: String,
- age: Number
- });
- // 创建模型
- const User = mongoose.model('User', userSchema);
- // 创建新用户
- const newUser = new User({
- name: 'John Doe',
- email: 'john@example.com',
- age: 30
- });
- // 保存用户到数据库
- newUser.save((err) => {
- if (err) {
- console.error(err);
- } else {
- console.log('User saved successfully!');
- }
- });
复制代码
dotenv用于从.env文件加载环境变量到process.env中。
示例代码:
- require('dotenv').config();
- // 现在可以通过process.env访问环境变量
- console.log(process.env.DB_HOST); // 输出: localhost
复制代码
Nodemon是一个工具,可在检测到目录中的文件更改时自动重新启动Node应用程序。
- npm install --save-dev nodemon
复制代码
在package.json中添加一个脚本:
- {
- "scripts": {
- "start": "nodemon index.js"
- }
- }
复制代码
然后运行:
5. 项目基础配置
目录结构设计
一个良好的目录结构可以使项目更易于维护和扩展。以下是一个常见的Node.js项目目录结构:
- my-node-project/
- ├── config/ # 配置文件
- │ ├── db.js # 数据库配置
- │ └── express.js # Express配置
- ├── controllers/ # 控制器
- │ └── userController.js
- ├── models/ # 数据模型
- │ └── userModel.js
- ├── routes/ # 路由
- │ └── userRoutes.js
- ├── services/ # 业务逻辑
- │ └── userService.js
- ├── utils/ # 工具函数
- │ └── validation.js
- ├── public/ # 静态文件
- │ ├── css/
- │ ├── js/
- │ └── images/
- ├── views/ # 视图文件(如果使用模板引擎)
- │ └── index.html
- ├── tests/ # 测试文件
- │ └── user.test.js
- ├── .env # 环境变量
- ├── .gitignore # Git忽略文件
- ├── app.js # 应用入口文件
- ├── package.json # 项目配置
- └── README.md # 项目说明
复制代码
环境变量配置
使用环境变量可以管理不同环境(开发、测试、生产)的配置。
1. 安装dotenv:
1. 在项目根目录创建.env文件:
- # .env
- PORT=3000
- DB_HOST=localhost
- DB_USER=admin
- DB_PASS=password
- NODE_ENV=development
复制代码
1. 在应用入口文件中加载环境变量:
- // app.js
- require('dotenv').config();
- const express = require('express');
- const app = express();
- const port = process.env.PORT || 3000;
- app.get('/', (req, res) => {
- res.send('Hello World!');
- });
- app.listen(port, () => {
- console.log(`Server running on port ${port}`);
- });
复制代码
1. 创建.env.example文件作为模板,提交到版本控制:
- # .env.example
- PORT=
- DB_HOST=
- DB_USER=
- DB_PASS=
- NODE_ENV=
复制代码
1. 在.gitignore中添加.env,防止敏感信息被提交:
- # .gitignore
- node_modules
- .env
复制代码
ESLint和Prettier配置
ESLint是一个JavaScript代码检查工具,Prettier是一个代码格式化工具。使用它们可以保持代码风格一致。
- npm install --save-dev eslint prettier eslint-config-prettier eslint-plugin-prettier
复制代码
按照提示选择适合你的配置选项。
在项目根目录创建.prettierrc文件,配置Prettier:
- {
- "semi": true,
- "trailingComma": "es5",
- "singleQuote": true,
- "printWidth": 80,
- "tabWidth": 2
- }
复制代码
在.eslintrc.json中添加以下配置:
- {
- "extends": [
- "eslint:recommended",
- "plugin:prettier/recommended"
- ],
- "plugins": ["prettier"],
- "rules": {
- "prettier/prettier": "error"
- }
- }
复制代码
在package.json中添加以下脚本:
- {
- "scripts": {
- "format": "prettier --write "**/*.{js,jsx}"",
- "lint": "eslint . --ext .js"
- }
- }
复制代码
运行以下命令来格式化和检查代码:
- npm run format
- npm run lint
复制代码
Git配置
在项目根目录创建.gitignore文件,指定要忽略的文件和目录:
- # Dependencies
- node_modules/
- # Environment variables
- .env
- # Logs
- logs
- *.log
- npm-debug.log*
- # Runtime data
- pids
- *.pid
- *.seed
- *.pid.lock
- # Coverage directory used by tools like istanbul
- coverage/
- # nyc test coverage
- .nyc_output
- # Grunt intermediate storage
- .grunt
- # Bower dependency directory
- bower_components
- # node-waf configuration
- .lock-wscript
- # Compiled binary addons
- build/Release
- # Dependency directories
- jspm_packages/
- # TypeScript v1 declaration files
- typings/
- # Optional npm cache directory
- .npm
- # Optional eslint cache
- .eslintcache
- # Optional REPL history
- .node_repl_history
- # Output of 'npm pack'
- *.tgz
- # Yarn Integrity file
- .yarn-integrity
- # dotenv environment variables file
- .env.test
- # parcel-bundler cache
- .cache
- .parcel-cache
- # next.js build output
- .next
- # nuxt.js build output
- .nuxt
- # vuepress build output
- .vuepress/dist
- # Serverless directories
- .serverless
- # FuseBox cache
- .fusebox/
- # DynamoDB Local files
- .dynamodb/
复制代码
在项目根目录创建README.md文件,提供项目的基本信息和使用说明:
- # My Node.js Project
- A brief description of your project.
- ## Features
- - Feature 1
- - Feature 2
- - Feature 3
- ## Installation
- 1. Clone the repository
- ```bash
- git clone https://github.com/yourusername/my-node-project.git
复制代码
1. Install dependenciescd my-node-project
npm install
2. Set up environment variablescp .env.example .env
# Edit .env with your configuration
3. Run the applicationnpm start
Install dependenciescd my-node-project
npm install
- cd my-node-project
- npm install
复制代码
Set up environment variables
- cp .env.example .env
- # Edit .env with your configuration
复制代码
Run the application
Usage
Provide instructions and examples for using your project.
API Documentation
Document your API endpoints here.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the ISC License.
- #### 提交初始代码
- ```bash
- git add .
- git commit -m "Initial commit"
复制代码
6. 创建一个简单的Node.js应用
现在,让我们创建一个简单的Express应用,整合前面所学的知识。
安装必要的依赖
- npm install express mongoose dotenv cors helmet morgan
- npm install --save-dev nodemon eslint prettier eslint-config-prettier eslint-plugin-prettier
复制代码
创建项目结构
- mkdir config controllers models routes services utils public
复制代码
配置文件
- 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(err.message);
- // Exit process with failure
- process.exit(1);
- }
- };
- module.exports = connectDB;
复制代码- const express = require('express');
- const cors = require('cors');
- const helmet = require('helmet');
- const morgan = require('morgan');
- const setupExpress = (app) => {
- // Middleware
- app.use(cors());
- app.use(helmet());
- app.use(morgan('combined'));
- app.use(express.json());
- app.use(express.urlencoded({ extended: true }));
- // Static files
- app.use(express.static('public'));
- };
- module.exports = setupExpress;
复制代码
模型
- const mongoose = require('mongoose');
- const UserSchema = new mongoose.Schema({
- name: {
- type: String,
- required: true,
- },
- email: {
- type: String,
- required: true,
- unique: true,
- },
- password: {
- type: String,
- required: true,
- },
- date: {
- type: Date,
- default: Date.now,
- },
- });
- module.exports = mongoose.model('user', UserSchema);
复制代码
控制器
- const User = require('../models/User');
- // @desc Get all users
- // @route GET /api/users
- exports.getUsers = async (req, res) => {
- try {
- const users = await User.find();
- res.json(users);
- } catch (err) {
- console.error(err.message);
- res.status(500).send('Server Error');
- }
- };
- // @desc Get a user by ID
- // @route GET /api/users/:id
- exports.getUserById = async (req, res) => {
- try {
- const user = await User.findById(req.params.id);
-
- if (!user) {
- return res.status(404).json({ msg: 'User not found' });
- }
-
- res.json(user);
- } catch (err) {
- console.error(err.message);
- res.status(500).send('Server Error');
- }
- };
- // @desc Create a user
- // @route POST /api/users
- exports.createUser = async (req, res) => {
- try {
- const { name, email, password } = req.body;
-
- const newUser = new User({
- name,
- email,
- password,
- });
-
- const user = await newUser.save();
- res.json(user);
- } catch (err) {
- console.error(err.message);
- res.status(500).send('Server Error');
- }
- };
- // @desc Update a user
- // @route PUT /api/users/:id
- exports.updateUser = async (req, res) => {
- try {
- const { name, email, password } = req.body;
-
- // Build user object
- const userFields = {};
- if (name) userFields.name = name;
- if (email) userFields.email = email;
- if (password) userFields.password = password;
-
- let user = await User.findById(req.params.id);
-
- if (!user) {
- return res.status(404).json({ msg: 'User not found' });
- }
-
- user = await User.findByIdAndUpdate(
- req.params.id,
- { $set: userFields },
- { new: true }
- );
-
- res.json(user);
- } catch (err) {
- console.error(err.message);
- res.status(500).send('Server Error');
- }
- };
- // @desc Delete a user
- // @route DELETE /api/users/:id
- exports.deleteUser = async (req, res) => {
- try {
- let user = await User.findById(req.params.id);
-
- if (!user) {
- return res.status(404).json({ msg: 'User not found' });
- }
-
- await User.findByIdAndRemove(req.params.id);
-
- res.json({ msg: 'User removed' });
- } catch (err) {
- console.error(err.message);
- res.status(500).send('Server Error');
- }
- };
复制代码
路由
- const express = require('express');
- const router = express.Router();
- const userController = require('../controllers/userController');
- // User routes
- router.route('/')
- .get(userController.getUsers)
- .post(userController.createUser);
- router.route('/:id')
- .get(userController.getUserById)
- .put(userController.updateUser)
- .delete(userController.deleteUser);
- module.exports = router;
复制代码
服务
- const User = require('../models/User');
- class UserService {
- async getAllUsers() {
- try {
- return await User.find();
- } catch (error) {
- throw new Error(`Error fetching users: ${error.message}`);
- }
- }
- async getUserById(id) {
- try {
- const user = await User.findById(id);
- if (!user) {
- throw new Error('User not found');
- }
- return user;
- } catch (error) {
- throw new Error(`Error fetching user: ${error.message}`);
- }
- }
- async createUser(userData) {
- try {
- const user = new User(userData);
- return await user.save();
- } catch (error) {
- throw new Error(`Error creating user: ${error.message}`);
- }
- }
- async updateUser(id, userData) {
- try {
- const user = await User.findByIdAndUpdate(id, userData, { new: true });
- if (!user) {
- throw new Error('User not found');
- }
- return user;
- } catch (error) {
- throw new Error(`Error updating user: ${error.message}`);
- }
- }
- async deleteUser(id) {
- try {
- const user = await User.findByIdAndDelete(id);
- if (!user) {
- throw new Error('User not found');
- }
- return { message: 'User deleted successfully' };
- } catch (error) {
- throw new Error(`Error deleting user: ${error.message}`);
- }
- }
- }
- module.exports = new UserService();
复制代码
工具函数
- // Email validation regex
- const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
- // Password validation regex (at least 8 characters, one uppercase, one lowercase, one number)
- const passwordRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
- const validateEmail = (email) => {
- return emailRegex.test(email);
- };
- const validatePassword = (password) => {
- return passwordRegex.test(password);
- };
- module.exports = {
- validateEmail,
- validatePassword,
- };
复制代码
入口文件
- require('dotenv').config();
- const express = require('express');
- const connectDB = require('./config/db');
- const setupExpress = require('./config/express');
- const userRoutes = require('./routes/userRoutes');
- // Initialize Express app
- const app = express();
- // Connect to Database
- connectDB();
- // Setup Express middleware
- setupExpress(app);
- // Define routes
- app.use('/api/users', userRoutes);
- // Define a simple route
- app.get('/', (req, res) => {
- res.send('API is running...');
- });
- // Define port
- const PORT = process.env.PORT || 3000;
- // Start server
- app.listen(PORT, () => {
- console.log(`Server running on port ${PORT}`);
- });
复制代码
环境变量文件
- PORT=3000
- MONGO_URI=mongodb://localhost:27017/myNodeApp
- NODE_ENV=development
复制代码
.gitignore
- # Dependencies
- node_modules/
- # Environment variables
- .env
- # Logs
- logs
- *.log
- npm-debug.log*
- # Runtime data
- pids
- *.pid
- *.seed
- *.pid.lock
- # Coverage directory used by tools like istanbul
- coverage/
- # nyc test coverage
- .nyc_output
- # Grunt intermediate storage
- .grunt
- # Bower dependency directory
- bower_components
- # node-waf configuration
- .lock-wscript
- # Compiled binary addons
- build/Release
- # Dependency directories
- jspm_packages/
- # TypeScript v1 declaration files
- typings/
- # Optional npm cache directory
- .npm
- # Optional eslint cache
- .eslintcache
- # Optional REPL history
- .node_repl_history
- # Output of 'npm pack'
- *.tgz
- # Yarn Integrity file
- .yarn-integrity
- # dotenv environment variables file
- .env.test
- # parcel-bundler cache
- .cache
- .parcel-cache
- # next.js build output
- .next
- # nuxt.js build output
- .nuxt
- # vuepress build output
- .vuepress/dist
- # Serverless directories
- .serverless
- # FuseBox cache
- .fusebox/
- # DynamoDB Local files
- .dynamodb/
复制代码
package.json
- {
- "name": "my-node-project",
- "version": "1.0.0",
- "description": "A sample Node.js project",
- "main": "app.js",
- "scripts": {
- "start": "node app.js",
- "dev": "nodemon app.js",
- "test": "echo "Error: no test specified" && exit 1",
- "format": "prettier --write "**/*.{js,jsx}"",
- "lint": "eslint . --ext .js"
- },
- "keywords": [
- "node",
- "express",
- "mongodb"
- ],
- "author": "Your Name",
- "license": "ISC",
- "dependencies": {
- "cors": "^2.8.5",
- "dotenv": "^10.0.0",
- "express": "^4.17.1",
- "helmet": "^4.6.0",
- "mongoose": "^6.0.12",
- "morgan": "^1.10.0"
- },
- "devDependencies": {
- "eslint": "^8.2.0",
- "eslint-config-prettier": "^8.3.0",
- "eslint-plugin-prettier": "^4.0.0",
- "nodemon": "^2.0.14",
- "prettier": "^2.4.1"
- }
- }
复制代码
README.md
- # My Node.js Project
- A sample Node.js project with Express and MongoDB.
- ## Features
- - User management (CRUD operations)
- - RESTful API
- - MongoDB integration
- - Environment variables configuration
- - Code linting and formatting
- ## Installation
- 1. Clone the repository
- ```bash
- git clone https://github.com/yourusername/my-node-project.git
复制代码
1. Install dependenciescd my-node-project
npm install
2. Set up environment variablescp .env.example .env
# Edit .env with your configuration
3. Make sure MongoDB is installed and running on your machine
4. Run the application
“`bashFor developmentnpm run dev
Install dependenciescd my-node-project
npm install
- cd my-node-project
- npm install
复制代码
Set up environment variables
- cp .env.example .env
- # Edit .env with your configuration
复制代码
Make sure MongoDB is installed and running on your machine
Run the application
“`bash
npm run dev
# For production
npm start
- ## API Endpoints
- ### Users
- - `GET /api/users` - Get all users
- - `GET /api/users/:id` - Get a user by ID
- - `POST /api/users` - Create a new user
- - `PUT /api/users/:id` - Update a user
- - `DELETE /api/users/:id` - Delete a user
- ## Contributing
- Contributions are welcome! Please feel free to submit a Pull Request.
- ## License
- This project is licensed under the ISC License.
复制代码
7. 调试技巧
使用console.log
最简单的调试方法是使用console.log输出变量和状态:
- console.log('Debug message');
- console.log('Variable value:', variable);
复制代码
使用Node.js调试器
Node.js内置了调试器,可以通过以下方式启动:
使用VS Code调试
VS Code提供了强大的调试工具:
1. 在VS Code中打开项目
2. 点击左侧活动栏的调试图标
3. 点击”创建launch.json文件”,选择Node.js环境
4. 在launch.json中配置调试选项:
- {
- "version": "0.2.0",
- "configurations": [
- {
- "type": "node",
- "request": "launch",
- "name": "Launch Program",
- "skipFiles": ["<node_internals>/**"],
- "program": "${workspaceFolder}\\app.js"
- }
- ]
- }
复制代码
1. 在代码中设置断点(点击行号左侧)
2. 按F5开始调试
使用Chrome DevTools调试
1. 启动应用时添加–inspect标志:
1. 打开Chrome浏览器,访问chrome://inspect
2. 在”Remote Target”部分找到你的Node.js应用,点击”inspect”
使用ndb调试
ndb是Google推出的Node.js调试工具,提供了更友好的调试界面:
1. 安装ndb:
1. 使用ndb启动应用:
使用Express调试中间件
在开发环境中,可以使用morgan中间件记录HTTP请求:
- const morgan = require('morgan');
- app.use(morgan('dev'));
复制代码
错误处理中间件
在Express应用中添加错误处理中间件:
- app.use((err, req, res, next) => {
- console.error(err.stack);
- res.status(500).send('Something broke!');
- });
复制代码
8. 部署准备
环境变量配置
在生产环境中,确保设置正确的环境变量:
- # .env.production
- PORT=8080
- MONGO_URI=mongodb://user:password@production-db.example.com:27017/myNodeApp
- NODE_ENV=production
复制代码
使用PM2管理进程
PM2是一个Node.js应用的进程管理器,可以帮助你保持应用永久运行。
1. 安装PM2:
1. 创建ecosystem.config.js文件:
- module.exports = {
- apps: [{
- name: 'my-node-app',
- script: 'app.js',
- instances: 'max',
- exec_mode: 'cluster',
- env: {
- NODE_ENV: 'development',
- PORT: 3000
- },
- env_production: {
- NODE_ENV: 'production',
- PORT: 8080
- }
- }]
- };
复制代码
1. 启动应用:
- # 开发环境
- pm2 start ecosystem.config.js --env development
- # 生产环境
- pm2 start ecosystem.config.js --env production
复制代码
1. 其他PM2命令:
- # 查看所有进程
- pm2 list
- # 停止应用
- pm2 stop my-node-app
- # 重启应用
- pm2 restart my-node-app
- # 删除应用
- pm2 delete my-node-app
- # 查看日志
- pm2 logs my-node-app
- # 监控应用
- pm2 monit
复制代码
使用Docker容器化应用
1. 创建Dockerfile:
- # 使用官方Node.js运行时作为父镜像
- FROM node:16-alpine
- # 设置工作目录
- WORKDIR /usr/src/app
- # 复制package.json和package-lock.json
- COPY package*.json ./
- # 安装应用依赖
- RUN npm install --only=production
- # 复制应用源代码
- COPY . .
- # 暴露端口
- EXPOSE 3000
- # 定义运行应用的命令
- CMD [ "node", "app.js" ]
复制代码
1. 创建.dockerignore文件:
- node_modules
- npm-debug.log
- .env
- .git
- .gitignore
- README.md
- Dockerfile
- .dockerignore
复制代码
1. 构建Docker镜像:
- docker build -t my-node-app .
复制代码
1. 运行Docker容器:
- docker run -p 3000:3000 --env-file .env my-node-app
复制代码
使用Nginx作为反向代理
在生产环境中,可以使用Nginx作为反向代理,处理静态文件、SSL终止和负载均衡。
1. 安装Nginx:
- # Ubuntu/Debian
- sudo apt update
- sudo apt install nginx
- # CentOS/RHEL
- sudo yum install epel-release
- sudo yum install nginx
复制代码
1. 配置Nginx:
- # /etc/nginx/sites-available/my-node-app
- server {
- listen 80;
- server_name example.com;
- location / {
- proxy_pass http://localhost:3000;
- proxy_http_version 1.1;
- proxy_set_header Upgrade $http_upgrade;
- proxy_set_header Connection 'upgrade';
- proxy_set_header Host $host;
- proxy_cache_bypass $http_upgrade;
- }
- location /static/ {
- alias /path/to/your/project/public/;
- expires 30d;
- }
- }
复制代码
1. 启用配置:
- sudo ln -s /etc/nginx/sites-available/my-node-app /etc/nginx/sites-enabled/
- sudo nginx -t
- sudo systemctl restart nginx
复制代码
9. 总结与进阶学习资源
总结
本教程详细介绍了如何从零开始搭建一个Node.js项目,包括:
1. 环境准备:安装Node.js和npm
2. 项目初始化:创建package.json文件
3. 依赖管理:安装和管理项目依赖
4. 项目基础配置:目录结构、环境变量、ESLint和Prettier配置、Git配置
5. 创建一个简单的Node.js应用:使用Express和MongoDB
6. 调试技巧:使用各种工具调试Node.js应用
7. 部署准备:使用PM2、Docker和Nginx部署应用
通过本教程,你应该能够轻松搭建一个结构良好、可维护的Node.js项目,并为进一步开发打下坚实的基础。
进阶学习资源
1. 官方文档Node.js官方文档Express官方文档MongoDB官方文档
2. Node.js官方文档
3. Express官方文档
4. MongoDB官方文档
5. 书籍《Node.js设计模式》- Mario Casciaro《深入浅出Node.js》- 朴灵《Node.js实战》- Mike Cantelon等
6. 《Node.js设计模式》- Mario Casciaro
7. 《深入浅出Node.js》- 朴灵
8. 《Node.js实战》- Mike Cantelon等
9. 在线课程Node.js, Express, MongoDB & More: The Complete Bootcamp 2021- UdemyLearn Node- Wes BosNode.js Master Class- StackSkills
10. Node.js, Express, MongoDB & More: The Complete Bootcamp 2021- Udemy
11. Learn Node- Wes Bos
12. Node.js Master Class- StackSkills
13. 博客和网站Node.js官方博客2ality- Dr. Axel Rauschmayer的博客StrongLoop- IBM的Node.js博客
14. Node.js官方博客
15. 2ality- Dr. Axel Rauschmayer的博客
16. StrongLoop- IBM的Node.js博客
17. YouTube频道Traversy MediaThe Net NinjaAcademind
18. Traversy Media
19. The Net Ninja
20. Academind
21. 社区Node.js RedditStack OverflowNode.js Discord服务器
22. Node.js Reddit
23. Stack Overflow
24. Node.js Discord服务器
官方文档
• Node.js官方文档
• Express官方文档
• MongoDB官方文档
书籍
• 《Node.js设计模式》- Mario Casciaro
• 《深入浅出Node.js》- 朴灵
• 《Node.js实战》- Mike Cantelon等
在线课程
• Node.js, Express, MongoDB & More: The Complete Bootcamp 2021- Udemy
• Learn Node- Wes Bos
• Node.js Master Class- StackSkills
博客和网站
• Node.js官方博客
• 2ality- Dr. Axel Rauschmayer的博客
• StrongLoop- IBM的Node.js博客
YouTube频道
• Traversy Media
• The Net Ninja
• Academind
社区
• Node.js Reddit
• Stack Overflow
• Node.js Discord服务器
通过这些资源,你可以继续深入学习Node.js的各种高级特性和最佳实践,成为一名优秀的Node.js开发者。 |
|