Node.js基础用法

一、基础用法与核心模块

1. 运行 Node.js 脚本

bash

复制代码
# 运行 JS 文件
node script.js

# 进入交互式环境(REPL)
node
2. 核心模块示例
文件系统(fs 模块)

javascript

复制代码
const fs = require('fs').promises; // 异步 Promise 版本
const path = require('path');

// 读取文件
async function readFile() {
  try {
    const content = await fs.readFile(path.join(__dirname, 'test.txt'), 'utf8');
    console.log(content);
  } catch (err) {
    console.error('读取失败:', err);
  }
}

// 写入文件
async function writeFile() {
  try {
    await fs.writeFile('output.txt', 'Hello Node.js', 'utf8');
    console.log('写入成功');
  } catch (err) {
    console.error('写入失败:', err);
  }
}
HTTP 服务器(http 模块)

javascript

复制代码
const http = require('http');

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

server.listen(3000, () => {
  console.log('服务器运行在 http://localhost:3000');
});
路径处理(path 模块)

javascript

复制代码
const path = require('path');

// 拼接路径
const fullPath = path.join(__dirname, 'src', 'app.js');
console.log(fullPath); // 输出绝对路径

// 解析路径
console.log(path.parse(fullPath)); // 输出路径详情(root、dir、base等)

二、包管理(npm/yarn/pnpm)

1. 初始化项目

bash

复制代码
# 创建 package.json
npm init -y  # 快速生成默认配置
yarn init -y
2. 安装依赖

bash

复制代码
# 生产依赖(会写入 dependencies)
npm install lodash
yarn add lodash

# 开发依赖(会写入 devDependencies)
npm install --save-dev eslint
yarn add --dev eslint

# 全局安装
npm install -g nodemon
yarn global add nodemon
3. 运行脚本(package.json)

package.json 中定义脚本:

json

复制代码
{
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",  // 热重载开发
    "test": "jest"
  }
}

运行脚本:

bash

复制代码
npm run start  # 或 npm start(简写)
yarn dev

三、模块化系统(CommonJS 与 ES Modules)

1. CommonJS 模块(默认)

javascript

复制代码
// 导出(module.exports)
// math.js
function add(a, b) { return a + b; }
module.exports = { add };

// 导入(require)
// app.js
const { add } = require('./math');
console.log(add(1, 2)); // 3
2. ES Modules(需配置)

package.json 中添加:

json

复制代码
{ "type": "module" }

使用 ES 模块语法:

javascript

复制代码
// 导出(export)
// math.js
export function add(a, b) { return a + b; }

// 导入(import)
// app.js
import { add } from './math.js'; // 必须带 .js 后缀
console.log(add(1, 2)); // 3

四、常用开发工具与配置

1. 热重载(nodemon)

监控文件变化并自动重启服务:

bash

复制代码
# 安装
npm install -g nodemon

# 运行
nodemon server.js  # 替代 node server.js
2. 环境变量(dotenv)

管理环境变量(如数据库密码):

bash

复制代码
npm install dotenv

创建 .env 文件:

env

复制代码
DB_HOST=localhost
DB_PORT=3306

在代码中使用:

javascript

复制代码
require('dotenv').config();
console.log(process.env.DB_HOST); // localhost
3. 调试配置(VS Code)

创建 .vscode/launch.json

json

复制代码
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "启动程序",
      "program": "${workspaceFolder}/server.js"
    }
  ]
}

按 F5 启动调试。

五、常用框架与库

1. Web 框架
  • Express(轻量):

    javascript

    复制代码
    const express = require('express');
    const app = express();
    
    app.get('/', (req, res) => {
      res.send('Hello Express');
    });
    
    app.listen(3000, () => console.log('服务启动在 3000 端口'));
  • Koa(Express 团队开发,更现代):

    javascript

    复制代码
    const Koa = require('koa');
    const app = new Koa();
    
    app.use(ctx => {
      ctx.body = 'Hello Koa';
    });
    
    app.listen(3000);
2. 数据库操作
  • MySQL (使用 mysql2):

    javascript

    复制代码
    const mysql = require('mysql2/promise');
    
    async function query() {
      const connection = await mysql.createConnection({
        host: 'localhost',
        user: 'root',
        database: 'test'
      });
      const [rows] = await connection.execute('SELECT * FROM users');
      console.log(rows);
    }
  • MongoDB (使用 mongoose):

    javascript

    复制代码
    const mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost:27017/test');
    
    const User = mongoose.model('User', { name: String });
    const user = new User({ name: 'Node.js' });
    await user.save();

六、命令行工具开发

使用 commander 库快速开发 CLI:

bash

复制代码
npm install commander

示例(cli.js):

javascript

复制代码
const { program } = require('commander');

program
  .version('1.0.0')
  .command('greet <name>')
  .description('问候用户')
  .action((name) => {
    console.log(`Hello, ${name}!`);
  });

program.parse(process.argv);

运行:

bash

复制代码
node cli.js greet World  # 输出 "Hello, World!"

七、常用配置文件

  1. .npmrc(npm 配置):

    ini

    复制代码
    registry=https://registry.npmmirror.com  # 切换为淘宝镜像
  2. eslintrc.js(代码规范):

    javascript

    复制代码
    module.exports = {
      env: { node: true, es2021: true },
      extends: 'eslint:recommended',
      parserOptions: { ecmaVersion: 'latest' },
    };
  3. jest.config.js(测试配置):

    javascript

    复制代码
    module.exports = {
      testEnvironment: 'node',
    };
相关推荐
醉方休25 分钟前
Node.js 精选:50 款文件处理与开发环境工具库
linux·运维·node.js
Hello.Reader4 小时前
Elasticsearch Node.js 客户端的安装
elasticsearch·node.js·vim
Juchecar5 小时前
跨端桌面框架 Tauri 架构原理 的通俗解读
javascript·node.js
断竿散人6 小时前
Node 版本管理工具全指南
前端·node.js
哈撒Ki6 小时前
快速入门zod4
前端·node.js
tianchang7 小时前
打造你的本地AI助手:基于RAG+向量数据库的智能问答系统
人工智能·设计模式·node.js
月舞之剑8 小时前
linux离线安装nodejs
linux·node.js
Hello.Reader10 小时前
用 Node.js 玩转 Elasticsearch从安装到增删改查
大数据·elasticsearch·node.js
华科云商xiao徐11 小时前
Node.js浏览器引擎+Python大脑的智能爬虫系统
爬虫·python·node.js
outsider_友人A1 天前
前端也想写后端(2)ORM框架以及数据库关系和操作
node.js·orm·nestjs