当前位置: 首页 > news >正文

Node.js自学速通---- 24-8-22 22-44

目录

  • 一、安装 Node.js
  • 二、Node.js 的基本概念
  • 三、创建第一个 Node.js 应用
  • 四、使用模块
  • 五、创建 HTTP 服务器
  • 六、案例:文件服务器

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境,可以让 JavaScript 在服务器端运行。

一、安装 Node.js

  1. 打开浏览器,访问 Node.js 官方网站(https://nodejs.org/)。
  2. 在官网首页,你可以看到“LTS”(长期支持版本)和“Current”(当前版本)两个选项。一般来说,选择 LTS 版本会更加稳定。
  3. 根据你的操作系统(Windows、macOS 或 Linux),下载相应的安装程序。
  4. 运行安装程序,按照提示完成安装。

安装完成后,可以在命令提示符或终端中输入以下命令来检查 Node.js 是否安装成功:

node -v

如果能正确显示 Node.js 和 npm(Node.js 的包管理工具)的版本号,说明安装成功。

二、Node.js 的基本概念

  1. 模块系统

    • Node.js 使用 CommonJS 模块规范,允许你将代码拆分成多个模块,以便更好地组织和管理代码。
    • 一个模块可以通过 require 函数引入其他模块,并通过 module.exportsexports 对象导出自己的功能。
  2. 事件驱动和非阻塞 I/O

    • Node.js 是事件驱动的,它使用异步编程模型,通过回调函数或 Promise 来处理异步操作。
    • Node.js 的非阻塞 I/O 使得它能够在处理大量并发连接时保持高效。
  3. 内置模块

    • Node.js 提供了许多内置模块,如 fs(文件系统)、http(HTTP 服务器和客户端)、path(路径处理)等,可以直接在你的代码中使用。(这也是比较常用的)

三、创建第一个 Node.js 应用

  1. 创建一个新的文件夹,并在该文件夹中创建一个名为 app.js 的文件。
  2. app.js 文件中,输入以下代码:
// 打印 "Hello, World!"
console.log('Hello, World!');
  1. 在命令提示符或终端中,进入到你创建的文件夹,并运行以下命令:
node app.js

你应该能在控制台中看到输出的 “Hello, World!”。

四、使用模块

  1. 在你的项目文件夹中,创建一个名为 math.js 的文件,并在其中输入以下代码:
function add(a, b) {return a + b;
}function subtract(a, b) {return a - b;
}module.exports = {add,subtract
};
  1. app.js 文件中,引入 math.js 模块,并使用其中的函数:
const math = require('./math');console.log(math.add(5, 3));
console.log(math.subtract(10, 4));
  1. 运行 app.js 文件,能看到输出的两个数字。

五、创建 HTTP 服务器

  1. app.js 文件中,输入以下代码:
const http = require('http');const server = http.createServer((req, res) => {res.writeHead(200, { 'Content-Type': 'text/plain' });res.end('Hello, Node.js!');
});const port = 3000;
server.listen(port, () => {console.log(`Server running at port ${port}`);
});
  1. 运行 app.js 文件,然后在浏览器中访问 http://localhost:3000,能看到 “Hello, Node.js!” 的文本。

六、案例:文件服务器

  1. 创建一个名为 fileServer.js 的文件,并输入以下代码:
const http = require('http');
const fs = require('fs');
const path = require('path');const server = http.createServer((req, res) => {const filePath = path.join(__dirname, 'public', req.url === '/'? 'index.html' : req.url);const extname = path.extname(filePath);let contentType = 'text/html';switch (extname) {case '.js':contentType = 'text/javascript';break;case '.css':contentType = 'text/css';break;case '.png':contentType = 'image/png';break;case '.jpg':contentType = 'image/jpeg';break;case '.gif':contentType = 'image/gif';break;}fs.readFile(filePath, (err, content) => {if (err) {if (err.code === 'ENOENT') {res.writeHead(404, { 'Content-Type': 'text/plain' });res.end('404 Not Found');} else {res.writeHead(500, { 'Content-Type': 'text/plain' });res.end('500 Internal Server Error');}} else {res.writeHead(200, { 'Content-Type': contentType });res.end(content, 'utf-8');}});
});const port = 8080;
server.listen(port, () => {console.log(`File server running at port ${port}`);
});
  1. 在项目文件夹中创建一个名为 public 的文件夹,并在其中创建一个 index.html 文件和一些其他的静态资源文件(如 CSS、JavaScript、图片等)。

  2. 运行 fileServer.js 文件,然后在浏览器中访问 http://localhost:8080,看到静态网页。

以下是对这段 Node.js 代码的详细解释:

一、引入模块

const http = require('http');
const fs = require('fs');
const path = require('path');

这里引入了三个核心模块:

  • http模块用于创建 HTTP 服务器。
  • fs模块用于与文件系统进行交互,比如读取文件。
  • path模块用于处理文件和目录的路径。

二、创建服务器

const server = http.createServer((req, res) => {//...
});

使用 http.createServer 创建了一个 HTTP 服务器,这个服务器接收一个回调函数作为参数。每当有新的 HTTP 请求到达服务器时,这个回调函数就会被调用,传入两个参数 req(代表请求对象)和 res(代表响应对象)。

三、确定文件路径和内容类型

const filePath = path.join(__dirname, 'public', req.url === '/'? 'index.html' : req.url);
const extname = path.extname(filePath);
let contentType = 'text/html';switch (extname) {case '.js':contentType = 'text/javascript';break;case '.css':contentType = 'text/css';break;case '.png':contentType = 'image/png';break;case '.jpg':contentType = 'image/jpeg';break;case '.gif':contentType = 'image/gif';break;
}
  • const filePath = path.join(__dirname, 'public', req.url === '/'? 'index.html' : req.url);:这行代码确定要服务的文件路径。它使用 path.join 方法将当前目录(__dirname)、“public”文件夹和请求的 URL 组合在一起。如果请求的 URL 是 /,则默认提供 “index.html” 文件。
  • const extname = path.extname(filePath);:获取文件的扩展名。
  • 根据文件扩展名设置不同的 contentType,以便客户端正确地识别和处理响应的内容类型。

四、读取文件并发送响应

fs.readFile(filePath, (err, content) => {if (err) {if (err.code === 'ENOENT') {res.writeHead(404, { 'Content-Type': 'text/plain' });res.end('404 Not Found');} else {res.writeHead(500, { 'Content-Type': 'text/plain' });res.end('500 Internal Server Error');}} else {res.writeHead(200, { 'Content-Type': contentType });res.end(content, 'utf-8');}
});
  • 使用 fs.readFile 方法读取确定的文件路径对应的文件内容。如果读取过程中出现错误:
    • 如果错误代码是 ENOENT,表示文件不存在,发送状态码 404 和 “404 Not Found” 的响应内容。
    • 如果是其他错误,发送状态码 500 和 “500 Internal Server Error” 的响应内容。
  • 如果成功读取到文件内容,发送状态码 200,并设置正确的 contentType,然后将文件内容作为响应发送给客户端。

五、启动服务器

const port = 8080;
server.listen(port, () => {console.log(`File server running at port ${port}`);
});

设置服务器监听的端口为 8080,当服务器成功启动后,在控制台打印出 “File server running at port 8080” 的消息。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • Java中的File类应用
  • Kubernetes Master节点:集群控制中心的解析
  • ARM——驱动——inmod加载内核模块
  • 微信小程序:点击事件(bindtap)传递参数
  • 新版本 | GreatSQL 8.0.32-26全新发布 增强“四高”诸多新特性
  • Python常用内置函数(二)
  • Java重修笔记 第四十天 List集合、ArrayList集合
  • Vue 3 的 emit 简单使用
  • 驱动开发系列13 - Linux Graphics 图形驱动概述(二)
  • SQL手工注入漏洞测试(MongoDB数据库)
  • Xmind 在线导图上线!多设备实时同步,节约本地空间
  • 【Kotlin】在Kotlin项目中使用AspectJ
  • Python核心编程--Python要点总结
  • Swift 内存管理:精通强、弱、无主之地
  • IOS半越狱工具nathanlr越狱教程
  • go语言学习初探(一)
  • Java IO学习笔记一
  • JavaScript标准库系列——Math对象和Date对象(二)
  • JavaScript设计模式与开发实践系列之策略模式
  • learning koa2.x
  • MySQL几个简单SQL的优化
  • Odoo domain写法及运用
  • PHP的类修饰符与访问修饰符
  • springMvc学习笔记(2)
  • Sublime Text 2/3 绑定Eclipse快捷键
  • thinkphp5.1 easywechat4 微信第三方开放平台
  • Vue 重置组件到初始状态
  • 给github项目添加CI badge
  • 关于 Cirru Editor 存储格式
  • 目录与文件属性:编写ls
  • 如何在GitHub上创建个人博客
  • 腾讯视频格式如何转换成mp4 将下载的qlv文件转换成mp4的方法
  • 新手搭建网站的主要流程
  • 组复制官方翻译九、Group Replication Technical Details
  • ​ 全球云科技基础设施:亚马逊云科技的海外服务器网络如何演进
  • ​LeetCode解法汇总307. 区域和检索 - 数组可修改
  • ​MPV,汽车产品里一个特殊品类的进化过程
  • ​数据链路层——流量控制可靠传输机制 ​
  • # 服务治理中间件详解:Spring Cloud与Dubbo
  • #!/usr/bin/python与#!/usr/bin/env python的区别
  • #《AI中文版》V3 第 1 章 概述
  • #QT(智能家居界面-界面切换)
  • #我与Java虚拟机的故事#连载09:面试大厂逃不过的JVM
  • (1)Jupyter Notebook 下载及安装
  • (14)目标检测_SSD训练代码基于pytorch搭建代码
  • (2)空速传感器
  • (2024)docker-compose实战 (9)部署多项目环境(LAMP+react+vue+redis+mysql+nginx)
  • (C)一些题4
  • (阿里云在线播放)基于SpringBoot+Vue前后端分离的在线教育平台项目
  • (二)原生js案例之数码时钟计时
  • (附源码)springboot优课在线教学系统 毕业设计 081251
  • (附源码)基于SpringBoot和Vue的厨到家服务平台的设计与实现 毕业设计 063133
  • (附源码)计算机毕业设计ssm本地美食推荐平台
  • (附源码)计算机毕业设计ssm高校《大学语文》课程作业在线管理系统
  • (三)终结任务