Node.js HTTP(S) module ----- Serving Files // WebServer 调用本地 文件 (基础)

本文详细介绍如何在Web服务器上通过Node.js调用并呈现本地HTML、CSS和图片文件,解决常见404错误,实现资源的有效管理和访问。

Serving Files 调用文件

Table of Contents

Serving Files 调用文件

拆分讲解

导入包

主方程扩展:

错误

完善 最终结果

结果


在这篇文章中, 主要讲述 如何 调用本地的文件在web server上

举个例子

本地 我们有html css 图片

然后我们收到了 request get 访问这些内容 我们要能顺利的将他们呈现给用户

上图中 

我们能看到在 public 这个文件夹中 包含 三个文件 一个JPD图片 一个HTML代码 一个CSS格式

我们在这就要去应用这些对象在我们的web server中

 


拆分讲解

导入包

第一步 我们会导入所需要的module http 或者 https(推荐)

然后fs 是filesystem 我们需要用它修改或者                                               

                        相关文章:https://blog.youkuaiyun.com/Cvan123/article/details/83280358

接下来path 我们需要用它得到 当前文件夹位置         

                        相关文章:https://mp.youkuaiyun.com/postedit/83099818                                

var http = require("http");
var fs = require("fs");
var path = require("path");

主方程扩展:

http.createServer(function(req, res) {

	console.log(`${req.method} request for ${req.url}`);

	if (req.url === "/") {
		fs.readFile("./public/index.html", "UTF-8", function(err, html) {
			res.writeHead(200, {"Content-Type": "text/html"});
			res.end(html);
		});

	}  else {
		res.writeHead(404, {"Content-Type": "text/plain"});
		res.end("404 File Not Found");
	}

}).listen(3000);


console.log("File server running on port 3000");

这是一个大致的框架包含处理分析

如果搜寻到当前领域不存在的文件 

会返回 404 File Not Found

readFile 以便去获得 HTML file中的所有代码  (File Stream是更好的选择 接下来会用到)

————————————

错误

但是这种code只能区分主页 和 非主页 

让我们来运行文件在 termial 中

Termial 运行 server:

打开浏览器运行

重返Termial

我们可以看到主页 在加载的同时 请求了 获取css jpg he ico 文件

——————————————————————————————————————————————

问题就来了

当我们尝试去获取css文件的时候 我们的code因为识别它不为主页

显示为404

我们可以确认它在浏览器中

——————————————————————————————————————————————

想要修复这个问题 我们需要对每个file进行识别

 


完善 最终结果

var http = require("http");
var fs = require("fs");
var path = require("path");

http.createServer(function(req, res) {

	console.log(`${req.method} request for ${req.url}`);

	if (req.url === "/") {
		fs.readFile("./public/index.html", "UTF-8", function(err, html) {
			res.writeHead(200, {"Content-Type": "text/html"});
			res.end(html);
		});

	} else if (req.url.match(/.css$/)) {

		var cssPath = path.join(__dirname, 'public', req.url);
		var fileStream = fs.createReadStream(cssPath, "UTF-8");

		res.writeHead(200, {"Content-Type": "text/css"});

		fileStream.pipe(res);

	} else if (req.url.match(/.jpg$/)) {

		var imgPath = path.join(__dirname, 'public', req.url);
		var imgStream = fs.createReadStream(imgPath);

		res.writeHead(200, {"Content-Type": "image/jpeg"});

		imgStream.pipe(res);

	} else {
		res.writeHead(404, {"Content-Type": "text/plain"});
		res.end("404 File Not Found");
	}

}).listen(3000);


console.log("File server running on port 3000");

在Else if 后面 我们首先检查 一串字符的通用表达式  后缀带有 css

res object是一个可写入的stream

fileStream.pipe(res); 

意味着filestream中读取的数据 会 自动带入res 并且自动结束

图片的请求同理去解决

结果

加载图片和主页成功以后

 


更多:

Author: Cvanzy 

在接下来文章中 我还会讨论更多这个话题

 

2025-10-23 09:29:49 - [MainThread] - INFO - (main.py:11) $ <module>) ::: start clean residual process... 2025-10-23 09:29:49 - [MainThread] - INFO - (clean_process.py:15) $ clean_process) ::: Closing process:RuntimeBroker.exe(PID:4900) 2025-10-23 09:29:49 - [MainThread] - INFO - (clean_process.py:15) $ clean_process) ::: Closing process:wps.exe(PID:5396) 2025-10-23 09:29:49 - [MainThread] - INFO - (clean_process.py:15) $ clean_process) ::: Closing process:wpscloudsvr.exe(PID:5964) 2025-10-23 09:29:49 - [MainThread] - INFO - (clean_process.py:15) $ clean_process) ::: Closing process:RuntimeBroker.exe(PID:10816) 2025-10-23 09:29:49 - [MainThread] - INFO - (clean_process.py:15) $ clean_process) ::: Closing process:RuntimeBroker.exe(PID:11464) 2025-10-23 09:29:49 - [MainThread] - INFO - (clean_process.py:15) $ clean_process) ::: Closing process:RuntimeBroker.exe(PID:11612) 2025-10-23 09:29:49 - [MainThread] - INFO - (clean_process.py:15) $ clean_process) ::: Closing process:wps.exe(PID:12296) 2025-10-23 09:29:49 - [MainThread] - INFO - (clean_process.py:15) $ clean_process) ::: Closing process:RuntimeBroker.exe(PID:14444) 2025-10-23 09:29:49 - [MainThread] - INFO - (main.py:14) $ <module>) ::: start agent... 2025-10-23 09:29:49 - [MainThread] - INFO - (server.py:39) $ restart) ::: restart ws 2025-10-23 09:29:49 - [MainThread] - INFO - (main.py:148) $ restart) ::: restart graph thread 2025-10-23 09:29:49 - [MainThread] - INFO - (main.py:153) $ restart) ::: start graph thread 2025-10-23 09:29:49 - [graph] - INFO - (main.py:49) $ init_graph) ::: load {'name': 'req_diff', 'type': 'req', 'desc': 'Requirement Diff Analysing, to compare requirement documents of two different versions', 'route_key': '需求差异分析(Requirement Diff Analysing)', 'steps': [{'node_name': 'req_diff_executor', 'funct_name': 'entry', 'module': 'robot.req_diff.entry'}]} 2025-10-23 09:29:49 - [Thread-4 (task_handler)] - INFO - (task_handler.py:2516) $ task_handler) ::: [task handler] sub thread start to run. 2025-10-23 09:29:49 - [ws] - INFO - (server.py:707) $ wrap) ::: server listening on 0.0.0.0:17011 2025-10-23 09:29:49 - [graph] - INFO - (main.py:49) $ init_graph) ::: load {'name': 'neo4j_diff', 'type': 'req', 'desc': 'Requirements Analysing, refers to a systematic process of analyzing a specific goal or issue to clarify its necessary conditions or critical elements', 'route_key': '要件分析(Requirement Analysing)', 'steps': [{'node_name': 'neo4j_diff_executor', 'funct_name': 'neo4j_diff', 'module': 'robot.neo4j_diff.neo4j_diff'}]} 2025-10-23 09:29:49 - [ws] - INFO - (server.py:63) $ _start_server) ::: WebSocket server started at ws://0.0.0.0:17011 2025-10-23 09:29:49 - [graph] - INFO - (main.py:49) $ init_graph) ::: load {'name': 'regulation_check', 'type': 'req', 'desc': 'Regulation Check, determine whether the change point requirements are compliant.', 'route_key': '合规性检查(Regulation Checking)', 'steps': [{'node_name': 'regulation_executor', 'funct_name': 'entry', 'module': 'robot.regulation_check.entry'}]} * Serving Flask app 'kotei_web_server.app' INFO: Started server process [12148] * Debug mode: on INFO: Waiting for application startup. INFO: Application startup complete. Exception in thread graph: INFO: Uvicorn running on http://0.0.0.0:17010 (Press CTRL+C to quit) Traceback (most recent call last): File "threading.py", line 1016, in _bootstrap_inner File "threading.py", line 953, in run 2025-10-23 09:29:50 - [Thread-3 (doc_web_server_main)] - INFO - (_internal.py:97) $ _log) ::: WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on all addresses (0.0.0.0) * Running on http://127.0.0.1:17012 * Running on http://192.168.192.146:17012 2025-10-23 09:29:50 - [Thread-3 (doc_web_server_main)] - INFO - (_internal.py:97) $ _log) ::: Press CTRL+C to quit File "kotei_agent\graph\main.py", line 122, in start_graph File "kotei_agent\graph\main.py", line 95, in init_graph File "importlib\__init__.py", line 126, in import_module File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module File "robot\req_diff\entry.py", line 23, in <module> File "D:\RRM\Packages\release-20251023\diff-agent\_internal\kotei_omc\compare_parser.py", line 3, in <module> from kotei_omc.comparers.plugins import compare_plugins File "D:\RRM\Packages\release-20251023\diff-agent\_internal\kotei_omc\comparers\__init__.py", line 1, in <module> from kotei_omc.comparers import text_comparer File "D:\RRM\Packages\release-20251023\diff-agent\_internal\kotei_omc\comparers\text_comparer.py", line 5, in <module> from kotei_omc.middlewares.text_middlewares import CustomTextStrategyMiddleware File "D:\RRM\Packages\release-20251023\diff-agent\_internal\kotei_omc\middlewares\text_middlewares.py", line 8, in <module> from sklearn.feature_extraction.text import TfidfVectorizer File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module File "sklearn\__init__.py", line 73, in <module> File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module File "sklearn\base.py", line 19, in <module> File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module File "sklearn\utils\__init__.py", line 15, in <module> File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module File "sklearn\utils\_chunking.py", line 11, in <module> File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module File "sklearn\utils\_param_validation.py", line 14, in <module> File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module File "scipy\sparse\__init__.py", line 300, in <module> File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module File "scipy\sparse\_base.py", line 5, in <module> File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module File "scipy\sparse\_sputils.py", line 10, in <module> File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module File "scipy\_lib\_util.py", line 13, in <module> File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module File "scipy\_lib\_array_api.py", line 18, in <module> File "PyInstaller\loader\pyimod02_importers.py", line 450, in exec_module File "scipy\_lib\array_api_compat\numpy\__init__.py", line 1, in <module> File "numpy\__init__.py", line 374, in __getattr__ ModuleNotFoundError: No module named 'numpy.f2py'
最新发布
10-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值