Node.js 基础教程

Node.js 基础教程

1. 什么是 Node.js?

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境,允许你在服务器端运行 JavaScript 代码。它是开源的、跨平台的,并且非常适合构建高性能、可扩展的网络应用程序。

2. 安装 Node.js

2.1 下载安装

  1. 访问官方网站 https://nodejs.org/
  2. 选择适合你操作系统的长期支持(LTS)版本
  3. 下载并运行安装程序
  4. 安装完成后,打开命令行并验证安装:
bash 复制代码
node --version
npm --version

2.2 通过包管理器安装

Windows

使用 Chocolatey:

bash 复制代码
choco install nodejs-lts
macOS

使用 Homebrew:

bash 复制代码
brew install node
Linux (Ubuntu/Debian)
bash 复制代码
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs

3. 基本概念和语法

3.1 创建第一个 Node.js 程序

创建 hello.js 文件:

javascript 复制代码
console.log('Hello, Node.js!');

在命令行运行:

bash 复制代码
node hello.js

3.2 模块系统

CommonJS 模块导入导出

math.js

javascript 复制代码
function add(a, b) {
    return a + b;
}

function subtract(a, b) {
    return a - b;
}

module.exports = {
    add,
    subtract
};

app.js

javascript 复制代码
const math = require('./math');

console.log(math.add(5, 3));      // 输出: 8
console.log(math.subtract(10, 4)); // 输出: 6

3.3 异步编程

回调函数
javascript 复制代码
function fetchData(callback) {
    setTimeout(() => {
        callback('数据已获取');
    }, 2000);
}

fetchData((result) => {
    console.log(result);
});
Promise
javascript 复制代码
function fetchDataPromise() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('数据已获取');
        }, 2000);
    });
}

fetchDataPromise()
    .then(result => console.log(result))
    .catch(error => console.error(error));
Async/Await
javascript 复制代码
async function getData() {
    try {
        const result = await fetchDataPromise();
        console.log(result);
    } catch (error) {
        console.error(error);
    }
}

getData();

4. NPM(Node Package Manager)

4.1 初始化项目

bash 复制代码
mkdir my-project
cd my-project
npm init -y

4.2 安装依赖

bash 复制代码
# 安装生产依赖
npm install express

# 安装开发依赖
npm install --save-dev nodemon

# 全局安装
npm install -g nodemon

4.3 package.json 脚本

json 复制代码
{
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js",
    "test": "jest"
  }
}

5. 常用内置模块

5.1 文件系统(fs)

javascript 复制代码
const fs = require('fs');

// 同步读取文件
const content = fs.readFileSync('file.txt', 'utf8');

// 异步读取文件
fs.readFile('file.txt', 'utf8', (err, data) => {
    if (err) throw err;
    console.log(data);
});

5.2 路径(path)

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

const filePath = path.join(__dirname, 'files', 'data.json');
console.log(filePath);

5.3 HTTP 模块

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

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

server.listen(3000, () => {
    console.log('服务器运行在 http://localhost:3000');
});

6. 搭建简单的 Web 服务器(Express)

6.1 安装 Express

bash 复制代码
npm install express

6.2 基本服务器

javascript 复制代码
const express = require('express');
const app = express();
const port = 3000;

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

app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
});

7. 最佳实践和建议

  1. 使用 constlet 替代 var
  2. 使用异步编程和 Promise
  3. 使用 async/await 处理异步操作
  4. 合理使用错误处理
  5. 保持代码模块化
  6. 使用 ESLint 进行代码风格检查

结语

Node.js 是现代 Web 开发不可或缺的技术。通过持续学习和实践,你将能够构建高效、可扩展的应用程序。

相关推荐
李明卫杭州9 小时前
React 复合事件系统对比解析
前端·javascript·react.js
LEE11 小时前
前端转型全栈 01:数据建模,前端最大的盲区
前端·javascript·后端
雪芽蓝域zzs11 小时前
第四十七节:驾驶舱大屏 ECharts 图表集成
前端·javascript·vue.js
梦醒沉醉12 小时前
7、表达日期和时间(前朝遗老Date)
javascript
雪芽蓝域zzs12 小时前
第四十九节:TagsView 右键菜单(带三角箭头)给每个 tag 增加**鼠标右键菜单**(右键标签弹出:关闭、关闭其他、关闭全部)
前端·javascript·vue.js
এ慕ོ冬℘゜13 小时前
从零开发移动端医院挂号页面:适配、交互与前端实现详解
前端·javascript
宁渡AI大模型13 小时前
AI 全栈面试新趋势:Vibe Coding、前端、Java 后端高频面试题深度解析|河南宁渡科技有限公司编程教程
java·javascript·人工智能·python·ai大模型
东风微鸣13 小时前
AI依赖更新别裸奔🚨
javascript
研☆香13 小时前
echarts图表的使用方法
javascript
是立不是利15 小时前
大文件导致请求被拒的连锁反应
开发语言·前端·javascript