0


前端node.js入门

(创作不易,感谢有你,你的支持,就是我前行的最大动力,如果看完对你有帮助,请留下您的足迹)

Node.js 入门概览

什么是Node.js?

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境,它允许开发者在服务器端运行 JavaScript 代码。Node.js 的出现极大地改变了 Web 开发的格局,使得前后端可以使用同一种语言进行开发,极大地提高了开发效率和团队协作的便捷性。

为什么选择Node.js?

  1. 事件驱动和非阻塞I/O:Node.js 使用了事件驱动和非阻塞I/O模型,使得它非常适合处理高并发请求,能够轻松处理成千上万的并发连接。
  2. 单线程:虽然 JavaScript 本身是单线程的,但 Node.js 利用了 V8 引擎的多线程能力进行底层操作,通过事件循环和回调函数处理异步操作,减少了线程切换的开销。
  3. 丰富的生态系统:npm(Node Package Manager)是世界上最大的开源库生态系统之一,拥有超过百万个包,覆盖了从开发工具到框架、库等各个方面。
  4. 跨平台:Node.js 支持多种操作系统,包括 Windows、Linux 和 macOS,使得开发的应用可以轻松部署到不同环境中。

基础安装与环境配置

安装Node.js

Node.js 可以从其官方网站下载安装包或通过包管理器进行安装。以 Ubuntu 系统为例,可以使用以下命令安装:

  1. curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
  2. sudo apt-get install -y nodejs

安装完成后,可以通过运行

  1. node -v

  1. npm -v

来检查 Node.js 和 npm 是否安装成功及其版本。

第一个Node.js应用

创建一个简单的HTTP服务器

创建一个名为

  1. app.js

的文件,并写入以下代码:

  1. const http = require('http');
  2. const server = http.createServer((req, res) => {
  3. res.writeHead(200, {'Content-Type': 'text/html'});
  4. res.end('<h1>Hello, World!</h1>');
  5. });
  6. server.listen(3000, () => {
  7. console.log('Server is running on http://localhost:3000');
  8. });

这段代码创建了一个 HTTP 服务器,监听 3000 端口,并对每一个请求返回一个简单的 HTML 页面。在终端中运行

  1. node app.js

,然后在浏览器中访问

  1. http://localhost:3000

,你应该能看到 "Hello, World!" 的页面。

核心模块与API

Node.js 提供了一系列核心模块,这些模块提供了基本的系统操作功能,如文件操作、网络编程、加密等。

文件系统(fs)模块

  1. fs

模块用于在 Node.js 中执行文件系统的操作,如读写文件、创建目录等。

  1. const fs = require('fs');
  2. fs.readFile('example.txt', 'utf8', (err, data) => {
  3. if (err) {
  4. console.error(err);
  5. return;
  6. }
  7. console.log(data);
  8. });
  9. // 异步写文件
  10. fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
  11. if (err) throw err;
  12. console.log('The file has been saved!');
  13. });

路径(path)模块

  1. path

模块提供了一些用于处理文件路径的实用工具。

  1. const path = require('path');
  2. let myPath = path.join(__dirname, 'subdir', 'myfile.txt');
  3. console.log(myPath);
  4. // 判断文件扩展名
  5. let ext = path.extname(myPath);
  6. console.log(ext);

异步编程

Node.js 本质上是异步的,掌握异步编程模式对于编写高效、可维护的 Node.js 应用至关重要。

回调函数

回调函数是 Node.js 中处理异步操作的传统方式。

  1. // 示例:setTimeout 的回调函数
  2. setTimeout(() => {
  3. console.log('This message will be displayed after 2 seconds');
  4. }, 2000);

Promises

Promises 提供了一种更强大、更灵活的方式来处理异步操作。

  1. new Promise((resolve, reject) => {
  2. // 模拟异步操作
  3. setTimeout(() => {
  4. const success = true; // 假设操作成功
  5. if (success) {
  6. resolve('Operation succeeded!');
  7. } else {
  8. reject('Operation failed!');
  9. }
  10. }, 1000);
  11. })
  12. .then(result => {
  13. console.log(result); // 'Operation succeeded!'
  14. return new Promise((resolve, reject) => {
  15. // 链式操作
  16. setTimeout(() => {
  17. resolve('Second operation succeeded!');
  18. }, 500);
  19. });
  20. })
  21. .then(result => {
  22. console.log(result); // 'Second operation succeeded!'
  23. })
  24. .catch(error => {
  25. console.error(error); // 捕获任何之前的 Promise 中的错误
  26. });

Async/Await

async/await 是建立在 Promise 之上的语法糖,它使得异步代码看起来和同步代码一样。

  1. async function fetchData() {
  2. try {
  3. const result = await new Promise((resolve, reject) => {
  4. setTimeout(() => {
  5. resolve('Data fetched successfully!');
  6. }, 1000);
  7. });
  8. console.log(result); // 'Data fetched successfully!'
  9. // 另一个异步操作
  10. const secondResult = await new Promise((resolve, reject) => {
  11. setTimeout(() => {
  12. resolve('Second data fetched successfully!');
  13. }, 500);
  14. });
  15. console.log(secondResult); // 'Second data fetched successfully!'
  16. } catch (error) {
  17. console.error(error);
  18. }
  19. }
  20. fetchData();

Node.js 框架与中间件

随着 Node.js 的流行,出现了许多框架和中间件,它们简化了 Web 应用的开发过程。

Express

Express 是最流行的 Node.js Web 应用框架之一,它提供了一套丰富的特性来帮助你创建各种 Web 应用和 API。

  1. const express = require('express');
  2. const app = express();
  3. const port = 3000;
  4. app.get('/', (req, res) => {
  5. res.send('Hello World!');
  6. });
  7. app.listen(port, () => {
  8. console.log(`Example app listening at http://localhost:${port}`);
  9. });

中间件

中间件是 Express 强大的功能之一,它允许你在请求-响应循环的特定阶段执行代码。

  1. const express = require('express');
  2. const app = express();
  3. // 日志中间件
  4. app.use((req, res, next) => {
  5. console.log(`${new Date()}: ${req.method} ${req.url}`);
  6. next(); // 不要忘记调用 next()
  7. });
  8. app.get('/', (req, res) => {
  9. res.send('Hello World!');
  10. });
  11. app.listen(3000, () => {
  12. console.log('Server is running on port 3000');
  13. });

数据库集成

Node.js 应用经常需要与数据库交互,幸运的是,有许多数据库和 Node.js 的集成方案可供选择。

MongoDB 与 Mongoose

MongoDB 是一个流行的 NoSQL 数据库,Mongoose 是一个 MongoDB 的对象数据模型(ODM)库,它为 MongoDB 数据提供了丰富的模型功能。

  1. const mongoose = require('mongoose');
  2. mongoose.connect('mongodb://localhost:27017/mydatabase', {
  3. useNewUrlParser: true,
  4. useUnifiedTopology: true
  5. });
  6. const Schema = mongoose.Schema;
  7. const userSchema = new Schema({
  8. name: String,
  9. age: Number
  10. });
  11. const User = mongoose.model('User', userSchema);
  12. // 创建一个新用户
  13. const newUser = new User({
  14. name: 'John Doe',
  15. age: 30
  16. });
  17. newUser.save().then(() => {
  18. console.log('User saved successfully!');
  19. }).catch(err => {
  20. console.error(err);
  21. });

错误处理

在 Node.js 应用中,错误处理是非常重要的。合理的错误处理可以确保应用的稳定性和可靠性。

基本的错误处理

  1. function readFile(filePath) {
  2. fs.readFile(filePath, 'utf8', (err, data) => {
  3. if (err) {
  4. console.error('Error reading file:', err);
  5. return;
  6. }
  7. console.log(data);
  8. });
  9. }

错误处理进阶

在Node.js中,错误处理不仅限于简单的回调函数中的错误参数检查。随着应用复杂性的增加,我们需要更加系统和全面的错误处理策略。

使用try/catch与async/await

当使用

  1. async/await

语法时,可以通过标准的

  1. try/catch

结构来捕获异步操作中的错误。

  1. async function readFileAsync(filePath) {
  2. try {
  3. const data = await fs.promises.readFile(filePath, 'utf8');
  4. console.log(data);
  5. } catch (error) {
  6. console.error('Error reading file:', error);
  7. }
  8. }
  9. readFileAsync('nonexistentfile.txt');

这里使用了

  1. fs.promises

接口,它是Node.js内置的

  1. fs

模块的一个承诺化版本,允许我们使用

  1. await

关键字。

错误传播

在Node.js中,错误传播是一个重要的概念。当一个函数遇到错误时,它应该将这个错误传递给它的调用者。这通常是通过回调函数的错误参数或在Promise链中通过

  1. reject

来完成的。

  1. function fetchUser(userId, callback) {
  2. // 模拟异步数据库查询
  3. setTimeout(() => {
  4. if (Math.random() > 0.5) {
  5. callback(new Error('User not found'));
  6. } else {
  7. callback(null, { id: userId, name: 'John Doe' });
  8. }
  9. }, 1000);
  10. }
  11. fetchUser(1, (err, user) => {
  12. if (err) {
  13. // 错误处理
  14. console.error('Failed to fetch user:', err);
  15. return;
  16. }
  17. console.log(user);
  18. });
  19. // 使用Promise的版本
  20. function fetchUserPromise(userId) {
  21. return new Promise((resolve, reject) => {
  22. setTimeout(() => {
  23. if (Math.random() > 0.5) {
  24. reject(new Error('User not found'));
  25. } else {
  26. resolve({ id: userId, name: 'John Doe' });
  27. }
  28. }, 1000);
  29. });
  30. }
  31. fetchUserPromise(1)
  32. .then(user => console.log(user))
  33. .catch(err => console.error('Failed to fetch user:', err));

自定义错误类型

在复杂的应用中,创建自定义错误类型可以使得错误处理更加清晰和灵活

  1. class UserNotFoundError extends Error {
  2. constructor(userId) {
  3. super(`User with ID ${userId} not found`);
  4. this.name = 'UserNotFoundError';
  5. }
  6. }
  7. function fetchUserWithCustomError(userId) {
  8. return new Promise((resolve, reject) => {
  9. setTimeout(() => {
  10. if (Math.random() > 0.5) {
  11. reject(new UserNotFoundError(userId));
  12. } else {
  13. resolve({ id: userId, name: 'John Doe' });
  14. }
  15. }, 1000);
  16. });
  17. }
  18. fetchUserWithCustomError(1)
  19. .then(user => console.log(user))
  20. .catch(err => {
  21. if (err instanceof UserNotFoundError) {
  22. console.error('User not found error:', err.message);
  23. } else {
  24. console.error('Unknown error:', err);
  25. }
  26. });
标签: 前端 node.js

本文转载自: https://blog.csdn.net/weixin_73295475/article/details/140743702
版权归原作者 小周不摆烂 所有, 如有侵权,请联系我们删除。

“前端node.js入门”的评论:

还没有评论