简体   繁体   English

使用fs.readFileSync()服务html文件失败

[英]Serve html file with fs.readFileSync() fails

I have this code ( https://gist.github.com/2402116 ) : 我有这个代码( https://gist.github.com/2402116 ):

server.get('/', function(request, response) {
 var k = fs.readFileSync('./index.html','utf8');
 response.send( k );
});

Tries to read this file: 尝试阅读此文件:

https://gist.github.com/2402070 https://gist.github.com/2402070

and the browser keeps loading and never end. 并且浏览器继续加载并且永远不会结束。

But if I remove all the js includes from the html file works fine. 但是,如果我从html文件中删除所有js包含工作正常。

what am I doing wrong? 我究竟做错了什么?

Your current server implementation does not do anything but serve index.html to requests for the base url, ie '/' . 当前的服务器实现不执行任何操作,只是将index.html给基本URL的请求,即'/' You will need to write further code/routes to serve the requests for the js includes in your index.html , ie '/app.js' and the various js files in '/js/' . 您需要编写更多代码/路由来为index.html的js包括请求,即'/app.js''/js/'的各种js文件。

Now, the routing implementation in the gist is quite crude and doesn't support many aspects of url matching. 现在,要点中的路由实现非常粗糙,并且不支持url匹配的许多方面。 The original code is clearly just demonstrating a concept for a single page site with no resources. 原始代码显然只是为没有资源的单个页面站点展示了一个概念。 You will see it will quickly become burdensome to get your code working as you will effectively have to write a route for every resource request, eg 您将看到很快就会让代码工作变得繁重,因为您将有效地为每个资源请求编写路由,例如

server.get('/app.js', function(request, response) {
  var k = fs.readFileSync('./app.js','utf8');
  response.send( k );
});

server.get('/js/jquery-1.7.2.js', function(request, response) {
  var k = fs.readFileSync('./js/jquery-1.7.2.js','utf8');
  response.send( k );
});

etc...

You are better off looking at a node.js url routing library already out there (eg director ) or a web framework such as express which has inbuilt support for routing (and static file serving). 你最好看看已经存在的node.js url路由库(例如director )或者像express这样内置支持路由 (和静态文件服务)的web框架。

You need a response.end() once you are done sending data to your browser. 完成向浏览器发送数据后,您需要response.end()

Actually, since you are sending all of your data at once, you can just replace response.send(k) with response.end(k) . 实际上,由于您一次发送所有数据,您只需将response.send(k)替换为response.end(k) Although this method is not recommended. 虽然不推荐这种方法。 I highly recommend reading your file asynchronously and sending it to the client chunk-by-chunk. 我强烈建议异步读取您的文件并将其发送到客户端chunk-by-chunk。

See also: http://nodejs.org/api/http.html#http_response_end_data_encoding 另见: http//nodejs.org/api/http.html#http_response_end_data_encoding

try .toString on k and not send but .end 在k上尝试.toString而不是发送.end

response.end( k.toString() ); 

maybe some wierd things happens and he tries to eval the code 也许一些奇怪的事情发生了,他试图评估代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM