gpt4 book ai didi

node.js - Node 本身可以​​在没有 express 或任何其他模块的情况下提供静态文件..?

转载 作者:搜寻专家 更新时间:2023-10-31 22:19:41 25 4
gpt4 key购买 nike

我是 Node js 领域的初学者。不知道如何从 url 发送简单请求喜欢:- http://localhost:9999/xyz/inde.html我的文件层次结构是

server.js
xyz(folder)-
|->index.html

并从我的服务器获取 html 页面。它在 9999 后运行

var http = require("http");
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.end();
}
http.createServer(onRequest).listen(9999);
console.log("Server has started.");

我知道我可以从 Node js 服务器发送字符串(具有 html 模板)并发送它作为响应,但是如何在没有 express 和任何其他外部模块的情况下发送文件。谢谢

最佳答案

尝试在没有 npm 依赖项的情况下创建 Node 应用程序是荒谬的,因为 nodejs 的基础就是——一个基础。除非你想实现整个协议(protocol),否则你最好使用一个最小的、维护良好的 npm 模块来为你做这件事。也就是说,这是您要求的最基本的东西(没有 MiME、eTag、缓存等):

var basePath = __dirname;
var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function(req, res) {
var stream = fs.createReadStream(path.join(basePath, req.url));
stream.on('error', function() {
res.writeHead(404);
res.end();
});
stream.pipe(res);
}).listen(9999);

关于node.js - Node 本身可以​​在没有 express 或任何其他模块的情况下提供静态文件..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28061080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com