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

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” 的消息。

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值