前端node.js入门

打印 上一主题 下一主题

主题 870|帖子 870|积分 2620

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

目录
Node.js 入门概览 
什么是Node.js?
为什么选择Node.js?
基础安装与环境设置
安装Node.js
第一个Node.js应用
创建一个简单的HTTP服务器
核心模块与API
文件系统(fs)模块
路径(path)模块
异步编程
回调函数
Promises
Async/Await
Node.js 框架与中间件
Express
中间件
数据库集成
MongoDB 与 Mongoose
错误处理处罚
基本的错误处理处罚
错误处理处罚进阶
利用try/catch与async/await
错误传播
自定义错误范例


Node.js 入门概览 

什么是Node.js?

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

   

  • 事件驱动和非阻塞I/O:Node.js 利用了事件驱动和非阻塞I/O模型,使得它非常适合处理处罚高并发哀求,能够轻松处理处罚成千上万的并发连接。
  • 单线程:固然 JavaScript 自己是单线程的,但 Node.js 利用了 V8 引擎的多线程能力举行底层利用,通过事件循环和回调函数处理处罚异步利用,减少了线程切换的开销。
  • 丰富的生态系统:npm(Node Package Manager)是世界上最大的开源库生态系统之一,拥有凌驾百万个包,覆盖了从开辟工具到框架、库等各个方面。
  • 跨平台: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
复制代码
安装完成后,可以通过运行 node -v 和 npm -v 来查抄 Node.js 和 npm 是否安装成功及其版本。
  第一个Node.js应用

创建一个简单的HTTP服务器

   创建一个名为 app.js 的文件,并写入以下代码:
  1. const http = require('http');  
  2.   
  3. const server = http.createServer((req, res) => {  
  4.   res.writeHead(200, {'Content-Type': 'text/html'});  
  5.   res.end('<h1>Hello, World!</h1>');  
  6. });  
  7.   
  8. server.listen(3000, () => {  
  9.   console.log('Server is running on http://localhost:3000');  
  10. });
复制代码
  这段代码创建了一个 HTTP 服务器,监听 3000 端口,并对每一个哀求返回一个简单的 HTML 页面。在终端中运行 node app.js,然后在欣赏器中访问 http://localhost:3000,你应该能看到 "Hello, World!" 的页面。
  核心模块与API

   Node.js 提供了一系列核心模块,这些模块提供了基本的系统利勤劳能,如文件利用、网络编程、加密等。
  文件系统(fs)模块

   fs 模块用于在 Node.js 中实行文件系统的利用,如读写文件、创建目录等。
  1. const fs = require('fs');  
  2.   
  3. fs.readFile('example.txt', 'utf8', (err, data) => {  
  4.   if (err) {  
  5.     console.error(err);  
  6.     return;  
  7.   }  
  8.   console.log(data);  
  9. });  
  10.   
  11. // 异步写文件  
  12. fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {  
  13.   if (err) throw err;  
  14.   console.log('The file has been saved!');  
  15. });
复制代码
路径(path)模块

   path 模块提供了一些用于处理处罚文件路径的实用工具。
  1. const path = require('path');  
  2.   
  3. let myPath = path.join(__dirname, 'subdir', 'myfile.txt');  
  4. console.log(myPath);  
  5.   
  6. // 判断文件扩展名  
  7. let ext = path.extname(myPath);  
  8. 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.     // 另一个异步操作  
  11.     const secondResult = await new Promise((resolve, reject) => {  
  12.       setTimeout(() => {  
  13.         resolve('Second data fetched successfully!');  
  14.       }, 500);  
  15.     });  
  16.     console.log(secondResult); // 'Second data fetched successfully!'  
  17.   } catch (error) {  
  18.     console.error(error);  
  19.   }  
  20. }  
  21.   
  22. 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.   
  5. app.get('/', (req, res) => {  
  6.   res.send('Hello World!');  
  7. });  
  8.   
  9. app.listen(port, () => {  
  10.   console.log(`Example app listening at http://localhost:${port}`);  
  11. });
复制代码
中间件

   中间件是 Express 强大的功能之一,它允许你在哀求-相应循环的特定阶段实行代码。
  1. const express = require('express');  
  2. const app = express();  
  3.   
  4. // 日志中间件  
  5. app.use((req, res, next) => {  
  6.   console.log(`${new Date()}: ${req.method} ${req.url}`);  
  7.   next(); // 不要忘记调用 next()  
  8. });  
  9.   
  10. app.get('/', (req, res) => {  
  11.   res.send('Hello World!');  
  12. });  
  13.   
  14. app.listen(3000, () => {  
  15.   console.log('Server is running on port 3000');  
  16. });
复制代码
数据库集成

   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.   
  7. const Schema = mongoose.Schema;  
  8.   
  9. const userSchema = new Schema({  
  10.   name: String,  
  11.   age: Number  
  12. });  
  13.   
  14. const User = mongoose.model('User', userSchema);  
  15.   
  16. // 创建一个新用户  
  17. const newUser = new User({  
  18.   name: 'John Doe',  
  19.   age: 30  
  20. });  
  21.   
  22. newUser.save().then(() => {  
  23.   console.log('User saved successfully!');  
  24. }).catch(err => {  
  25.   console.error(err);  
  26. });
复制代码
错误处理处罚

   在 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

   当利用async/await语法时,可以通过尺度的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.   
  10. readFileAsync('nonexistentfile.txt');
复制代码
  这里利用了fs.promises接口,它是Node.js内置的fs模块的一个答应化版本,允许我们利用await关键字。
  错误传播

   在Node.js中,错误传播是一个重要的概念。当一个函数遇到错误时,它应该将这个错误传递给它的调用者。这通常是通过回调函数的错误参数或在Promise链中通过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.   
  12. fetchUser(1, (err, user) => {  
  13.   if (err) {  
  14.     // 错误处理  
  15.     console.error('Failed to fetch user:', err);  
  16.     return;  
  17.   }  
  18.   console.log(user);  
  19. });  
  20.   
  21. // 使用Promise的版本  
  22. function fetchUserPromise(userId) {  
  23.   return new Promise((resolve, reject) => {  
  24.     setTimeout(() => {  
  25.       if (Math.random() > 0.5) {  
  26.         reject(new Error('User not found'));  
  27.       } else {  
  28.         resolve({ id: userId, name: 'John Doe' });  
  29.       }  
  30.     }, 1000);  
  31.   });  
  32. }  
  33.   
  34. fetchUserPromise(1)  
  35.   .then(user => console.log(user))  
  36.   .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.   
  8. function fetchUserWithCustomError(userId) {  
  9.   return new Promise((resolve, reject) => {  
  10.     setTimeout(() => {  
  11.       if (Math.random() > 0.5) {  
  12.         reject(new UserNotFoundError(userId));  
  13.       } else {  
  14.         resolve({ id: userId, name: 'John Doe' });  
  15.       }  
  16.     }, 1000);  
  17.   });  
  18. }  
  19.   
  20. fetchUserWithCustomError(1)  
  21.   .then(user => console.log(user))  
  22.   .catch(err => {  
  23.     if (err instanceof UserNotFoundError) {  
  24.       console.error('User not found error:', err.message);  
  25.     } else {  
  26.       console.error('Unknown error:', err);  
  27.     }  
  28.   });
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

泉缘泉

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表