1. 环境准备

首先确保你的系统已经安装了 Node.js:

# 检查 Node.js 是否安装
node --version

# 检查 npm 是否安装
npm --version

如果未安装,请从 Node.js 官网 下载安装。

2. 创建基础 Node.js 项目

方法一:手动创建项目

  1. 创建项目目
mkdir my-node-project
cd my-node-project
  1. 初始化 package.json

npm init -y

这会创建包含项目信息的 package.json 文件。

  1. 创建入口文件
# 创建主文件
touch app.js
  1. 编写基础代码
// app.js
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, Node.js!');
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});
  1. 运行项目

node app.js

方法二:使用 Express 框架

  1. 初始化并安装 Express
npm init -y
npm install express
  1. 创建 Express 应用
// app.js
const express = require('express');
const app = express();
const PORT = 3000;

app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

app.listen(PORT, () => {
  console.log(`Express server running at http://localhost:${PORT}`);
});

3. 完整的项目结构示例

my-node-project/
├── package.json
├── app.js
├── src/
│   ├── controllers/
│   ├── models/
│   ├── routes/
│   └── middleware/
├── public/
│   ├── css/
│   ├── js/
│   └── images/
├── views/
├── config/
├── tests/
└── README.md

4. 完整的 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": "jest"
  },
  "keywords": ["node", "express"],
  "author": "Your Name",
  "license": "MIT",
  "dependencies": {
    "express": "^4.18.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.0"
  }
}

5. 常用命令和工具

安装依赖

# 生产依赖
npm install express mongoose

# 开发依赖
npm install --save-dev nodemon jest

# 全局安装
npm install -g nodemon

有用的开发工具

# 自动重启开发服务器
npm install --save-dev nodemon

# 环境变量管理
npm install dotenv

# 代码格式化
npm install --save-dev prettier

# 代码检查
npm install --save-dev eslint

6. 完整的 Express 项目示例

// app.js
const express = require('express');
const path = require('path');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));

// 路由
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'views', 'index.html'));
});

app.get('/api/users', (req, res) => {
  res.json({ message: 'User data', users: [] });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong!');
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

7. 开发工作流建议

  1. 使用 Git 进行版本控制
git init
git add .
git commit -m "Initial commit"
  1. 创建 .gitignore 文件
node_modules/
.env
*.log
.DS_Store
  1. 创建 .env 文件
PORT=3000
DB_URL=mongodb://localhost:27017/mydb
JWT_SECRET=your-secret-key

8. 部署准备

使用 PM2 进行进程管理

npm install -g pm2

# 启动应用
pm2 start app.js

# 保存配置
pm2 save
pm2 startup
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐