什么是node.js 小白也能看明白

23 阅读2分钟

Node.js = JavaScript 运行环境

核心概念:什么是"运行环境"

类比 1:人类语言

txt
中文        需要      中国人/翻译官      才能理解
JavaScript  需要      运行环境          才能执行

类比 2:播放器

txt
MP4 视频文件  →  需要视频播放器  →  才能播放
.js 代码文件  →  需要 JS 运行环境  →  才能执行

JavaScript 的两个运行环境

1. 浏览器(传统环境)

javascript
// test.js
console.log('Hello');
alert('弹窗');
document.body.style.color = 'red';

怎么运行

html
<script src="test.js"></script>

浏览器提供的能力

  • window 对象
  • document 对象(操作页面)
  • alert() 函数
  • fetch() 网络请求
  • localStorage 本地存储

2. Node.js(服务端环境)

javascript
// test.js
console.log('Hello');
const fs = require('fs'); // 读写文件
const http = require('http'); // 创建服务器

怎么运行

bash
$ node test.js
Hello

Node.js 提供的能力

  • fs 模块(读写文件)
  • http 模块(网络服务)
  • path 模块(路径处理)
  • process 对象(进程信息)
  • 访问操作系统 API

对比理解

特性浏览器环境Node.js 环境
执行方式嵌入 HTML 中命令行执行 node xxx.js
核心能力操作网页 DOM操作文件系统、网络
全局对象windowglobal
用途前端开发后端开发、工具开发
典型 APIalert(), documentfs.readFile(), http.createServer()

深入理解:Node.js 的组成

txt
Node.js = V8 引擎 + C++ 扩展库 + JavaScript 标准库

1. V8 引擎(核心)

  • Google 开发的 JavaScript 引擎
  • 将 JS 代码编译成机器码执行
  • 浏览器 Chrome 也用 V8

2. C++ 扩展库

  • 文件系统操作(libuv)
  • 网络通信
  • 加密/解密
  • 压缩/解压

3. JavaScript 标准库

javascript
const fs = require('fs');      // 文件系统
const http = require('http');  // HTTP 服务
const path = require('path');  // 路径处理

为什么 JavaScript 需要"运行环境"

JavaScript 特点

javascript
// JavaScript 本身只是"语法规则"
let a = 1;
function add(x, y) { return x + y; }

JavaScript 不能直接

  • ❌ 读写文件
  • ❌ 创建服务器
  • ❌ 操作网页
  • ❌ 访问数据库

运行环境提供"超能力"

javascript
// 浏览器环境提供的能力
document.getElementById('app'); // ← document 是浏览器给的
// Node.js 环境提供的能力
require('fs').readFileSync('file.txt'); // ← fs 是 Node.js 给的

实际例子

代码:same.js

javascript
console.log('当前时间:'new Date());
console.log('1 + 1 ='1 + 1);

在浏览器运行

html
<script src="same.js"></script>

输出到浏览器控制台 ✅

在 Node.js 运行

bash
$ node same.js

输出到终端命令行 ✅


代码:browser-only.js

javascript
alert('Hello')// ← 浏览器专属 API

在浏览器运行:✅ 弹窗
在 Node.js 运行:❌ 报错 alert is not defined


代码:node-only.js

javascript
const fs = require('fs'); // ← Node.js 专属 API
console.log(fs.readFileSync('test.txt''utf-8'));

在 Node.js 运行:✅ 输出文件内容
在浏览器运行:❌ 报错 require is not defined

Node.js 软件的安装

bash
# 查看是否安装
$ node -v
v18.17.0
# 查看安装路径

Node.js 就是一个可执行程序

txt
/usr/local/bin/node  ← 这是一个软件
    ↓
类似于:
/Applications/Chrome.app
/Applications/VSCode.app

核心总结

概念解释
JavaScript编程语言(只是语法规则)
运行环境能够"执行"JS 代码的程序
Node.js一个可以在服务器/电脑上运行 JS 的软件
npm start用 Node.js 执行 ice.js 工具

一句话理解

Node.js 就像是一个"翻译官",它能读懂 JavaScript 代码,并把代码变成计算机能执行的指令。

txt
你写的 JS 代码(人类语言)
        ↓
    Node.js(翻译官)
        ↓
  机器码(计算机语言)

没有 Node.js,你的 .js 文件就只是一个文本文件,无法运行。
就像没有视频播放器,你的 .mp4 文件只能看文件图标,无法播放一样。