欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 会展 > Node.js 基础教程

Node.js 基础教程

2025/2/5 20:57:39 来源:https://blog.csdn.net/wscfan/article/details/144186992  浏览:    关键词: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. 安装完成后,打开命令行并验证安装:
node --version
npm --version

2.2 通过包管理器安装

Windows

使用 Chocolatey:

choco install nodejs-lts
macOS

使用 Homebrew:

brew install node
Linux (Ubuntu/Debian)
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 文件:

console.log('Hello, Node.js!');

在命令行运行:

node hello.js

3.2 模块系统

CommonJS 模块导入导出

math.js

function add(a, b) {return a + b;
}function subtract(a, b) {return a - b;
}module.exports = {add,subtract
};

app.js

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

3.3 异步编程

回调函数
function fetchData(callback) {setTimeout(() => {callback('数据已获取');}, 2000);
}fetchData((result) => {console.log(result);
});
Promise
function fetchDataPromise() {return new Promise((resolve, reject) => {setTimeout(() => {resolve('数据已获取');}, 2000);});
}fetchDataPromise().then(result => console.log(result)).catch(error => console.error(error));
Async/Await
async function getData() {try {const result = await fetchDataPromise();console.log(result);} catch (error) {console.error(error);}
}getData();

4. NPM(Node Package Manager)

4.1 初始化项目

mkdir my-project
cd my-project
npm init -y

4.2 安装依赖

# 安装生产依赖
npm install express# 安装开发依赖
npm install --save-dev nodemon# 全局安装
npm install -g nodemon

4.3 package.json 脚本

{"scripts": {"start": "node app.js","dev": "nodemon app.js","test": "jest"}
}

5. 常用内置模块

5.1 文件系统(fs)

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)

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

5.3 HTTP 模块

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

npm install express

6.2 基本服务器

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 开发不可或缺的技术。通过持续学习和实践,你将能够构建高效、可扩展的应用程序。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com