节点本身可以​​提供静态文件没有明确或任何其他模块..?

我是节点j的领域的初学者。不知道如何发送简单的请求从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."); 

我知道我可以从节点js服务器发送string(有html模板),并发送它作为响应,但如何发送文件没有快递和任何其他外部模块。 谢谢

尝试创build没有npm依赖关系的节点应用程序是很荒谬的,因为nodejs的基础就是这个基础。 除非你喜欢实现整个协议,否则最好使用一个最小的,维护良好的npm模块来为你做。 这就是说,这是你要求的基本的东西(没有MiME,eTags,caching等等):

 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); 

它非常简单,节点已经提供了fs模块,你可以从中读取这个html文件,并在响应obj上追加这样的内容:

 response.writeHead(200, {"Content-Type": "text/plain"}); //here is the code required fs.readFile("./xyz/index.html", (err,fileContent) => { response.end(fileContent); }); 

但这里的问题是你只会得到HTML文档,而不是那些存储在不同文件夹中的HTML文件中的资源,就像你在index.html中有这样的代码一样

<link rel="stylesheet" href="../css/index.css" />

这个index.css将不被节点服务器所允许。 但我想你的问题解决了。

 const http = require('http'); const fs = require("fs"); const path = require("path"); function send404(response){ response.writeHead(404, {'Content-Type': 'text/plain'}); response.write('Error 404: Resource not found.'); response.end(); } const mimeLookup = { '.js': 'application/javascript', '.html': 'text/html' }; const server = http.createServer((req, res) => { if(req.method == 'GET'){ let fileurl; if(req.url == '/'){ fileurl = 'index.html'; }else{ fileurl = req.url; } let filepath = path.resolve('./' + fileurl); let fileExt = path.extname(filepath); let mimeType = mimeLookup[fileExt]; if(!mimeType) { send404(res); return; } fs.exists(filepath, (exists) => { if(!exists){ send404(res); return; } res.writeHead(200, {'Content-Type': mimeType}); fs.createReadStream(filepath).pipe(res); }); } }).listen(3000); console.log("Server running at port 3000");