Nodejs实现的一个静态服务器实例

yizhihongxing

下面是Node.js实现的静态服务器的攻略:

准备工作

在实现静态服务器之前,需要在本地先准备好一些资源,例如图片、html文件等。这些资源需要保存在一个文件夹中,并且需要记住该文件夹的路径,以便后续使用。

实现过程

第一步:导入依赖

在实现一个Node.js服务器时,需要导入http和fs(文件系统)模块。http模块用于开启服务器,fs模块用于读取文件。

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

第二步:开启服务器

创建一个http服务器,并监听在其中。

const server = http.createServer((req, res) => { 
  // 程序接收请求并响应内容
}
server.listen(3000, () => { // 服务器监听端口为 3000
  console.log('Server running at http://localhost:3000');
});

第三步:程序接收请求并响应内容

在服务器接收到请求时,程序应该做出相应处理并返回相应内容。对于静态服务器,程序应该返回请求的文件内容。

const server = http.createServer((req, res) => { 
  const filePath = `.${req.url}`; // 获取文件路径
  fs.readFile(filePath, (err, data) => { // 读取文件
    if (err) { // 如果文件读取失败
      res.writeHead(404, {'Content-Type': 'text/plain'}); // 返回响应码 404
      res.write('404 Not Found'); // 返回响应内容
      res.end(); // 结束响应
    } else { // 如果文件读取成功
      res.writeHead(200); // 返回响应码 200
      res.write(data); // 返回响应内容
      res.end(); // 结束响应
    }
  });
});

示例一:返回静态html页面

const server = http.createServer((req, res) => {
  const filePath = `.${req.url}`; // 获取文件路径
  if (req.url === '/index.html') { // 当请求的资源为 index.html 时
    fs.readFile('./index.html', {encoding: 'utf-8'}, (err, data) => { // 读取index.html文件
      res.writeHead(200, {'Content-Type': 'text/html'}); // 返回html响应头
      res.write(data); // 返回html内容
      res.end(); // 结束响应
    });
  } else { // 其他情况,返回404错误
    res.writeHead(404, {'Content-Type': 'text/plain'}); // 返回响应码 404
    res.write('404 Not Found'); // 返回响应内容
    res.end(); // 结束响应
  }
});

示例二:返回静态图片

const server = http.createServer((req, res) => {
  const filePath = `.${req.url}`; // 获取文件路径
  const imageTypes = ['.jpg', '.jpeg', '.png']; // 定义支持的图片类型
  if (imageTypes.includes(filePath.slice(-4))) { // 当请求的资源为图片时
    fs.readFile(filePath, (err, data) => { // 读取图片
      if (err) { // 如果文件读取失败
        res.writeHead(404, {'Content-Type': 'text/plain'}); // 返回响应码 404
        res.write('404 Not Found'); // 返回响应内容
        res.end(); // 结束响应
      } else { // 如果文件读取成功
        res.writeHead(200, {'Content-Type': `image/${filePath.slice(-3)}`}); // 返回响应头,使用slice获取图片类型
        res.write(data); // 返回响应内容
        res.end(); // 结束响应
      }
    });
  } else { // 其他情况,返回404错误
    res.writeHead(404, {'Content-Type': 'text/plain'}); // 返回响应码 404
    res.write('404 Not Found'); // 返回响应内容
    res.end(); // 结束响应
  }
});

完整代码

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

const server = http.createServer((req, res) => {
  const filePath = `.${req.url}`;
  const imageTypes = ['.jpg', '.jpeg', '.png'];
  if (imageTypes.includes(filePath.slice(-4))) {
    fs.readFile(filePath, (err, data) => {
      if (err) {
        res.writeHead(404, {'Content-Type': 'text/plain'});
        res.write('404 Not Found');
        res.end();
      } else {
        res.writeHead(200, {'Content-Type': `image/${filePath.slice(-3)}`});
        res.write(data);
        res.end();
      }
    });
  } else if (req.url === '/index.html') {
    fs.readFile('./index.html', {encoding: 'utf-8'}, (err, data) => {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write(data);
      res.end();
    });
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.write('404 Not Found');
    res.end();
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Nodejs实现的一个静态服务器实例 - Python技术站

(0)
上一篇 2023年6月8日
下一篇 2023年6月8日

相关文章

  • NodeJS中利用Promise来封装异步函数

    Node.js中利用Promise来封装异步函数是常用的技巧。Promise解决了JavaScript异步回调的问题,提供了更加优雅的方式来处理异步操作。下面是实现这种封装的完整攻略: 理解Promise的基础 在Promise中,通过将一个异步操作封装成Promise对象,可以方便地使用链式调用的方式来处理异步回调函数。一个Promise对象有三个状态: …

    node js 2023年6月8日
    00
  • Node.js巧妙实现Web应用代码热更新

    Node.js 巧妙实现 Web 应用代码热更新可以通过 nodemon 这个工具来实现,具体步骤如下: 1. 安装 nodemon nodemon 是一个基于 Node.js 开发的工具,能够自动监控 Node.js 应用的服务更改,并在更改后重启 Node.js 应用程序。因此,我们需要先在本地安装 nodemon。在命令行中输入以下命令: npm in…

    node js 2023年6月8日
    00
  • Node升级后vue项目node-sass报错问题及解决

    针对该问题,下面给出详细的解决攻略: 问题描述 在升级 Node 版本后,运行 Vue 项目时,可能会出现以下报错: Error: Node Sass could not find a binding for your current environment: Windows 64-bit with Node.js 12.x Found bindings f…

    node js 2023年6月8日
    00
  • nodejs处理http请求实例详解之get和post

    Node.js处理HTTP请求实例详解之GET和POST 什么是HTTP请求? HTTP(Hyper Text Transfer Protocol)即超文本传输协议。它是Web客户端和服务器端进行通信的基础,它的主要特点是简单快速、灵活,是全球互联网的基础。 Node.js处理HTTP请求 Node.js是一个开源的、跨平台的JavaScript运行环境,它…

    node js 2023年6月8日
    00
  • node将geojson转shp返回给前端的实现方法

    要实现“node将geojson转shp返回给前端”的功能,可以采用以下步骤: 安装相关依赖 在Node.js中,我们可以使用geojson2shp库将GeoJSON文件转换为Shapefile文件。首先需要在命令行中安装该库,命令如下: npm install geojson2shp –save 创建服务器 使用Node.js创建一个简单的服务器,监听前…

    node js 2023年6月8日
    00
  • 如何用Node写页面爬虫的工具集

    如何用Node写页面爬虫的工具集? 一、准备工作 安装Node.js环境。 安装Node.js的包管理器npm,安装方法为在终端中输入npm install npm -g。 安装request、cheerio、iconv-lite等Node模块,这些模块用于发起网络请求、解析HTML页面内容和处理编码问题,命令行方式为npm install request …

    node js 2023年6月8日
    00
  • 基于nodejs+express4.X实现文件下载的实例代码

    让我来为您详细讲解如何基于 nodejs + express4.X 实现文件下载的实例代码。 一、安装 express 和 express-download 在使用 Express 实现文件下载前,需要先安装 express 和 express-download 这两个包: npm install express express-download –sav…

    node js 2023年6月8日
    00
  • node.js中ws模块创建服务端与客户端实例代码

    下面是关于“node.js中ws模块创建服务端与客户端实例代码”的完整攻略。 1. 安装ws模块 在开始使用ws模块之前,需要安装ws模块,可以使用npm进行安装。 npm install ws –save 2. 创建WebSocket服务端 首先需要引入ws模块,然后创建一个WebSocketServer对象,监听指定的端口。 示例代码: const W…

    node js 2023年6月8日
    00
合作推广
合作推广
分享本页
返回顶部