ITeye博客

node.js 读取文件

wangdf_jee · 2012-02-07 15:37 · node.js · 编程语言 · Markdown


var sys = require("sys"),  
      http = require("http"),  
      url = require("url"),  
      path = require("path"),  
      fs = require("fs");  
 
  http.createServer(function(request, response) {  
      var uri = url.parse(request.url).pathname;  
         console.log(uri);
      var filename = path.join(process.cwd(), uri);  
          console.log(filename);
      path.exists(filename, function(exists) {  
          if(!exists) {  
              response.writeHeader(404, {"Content-Type": "text/plain"});  
              response.write("404 Not Found\n");  
              response.end();  
              return;  
          }  
    
          fs.readFile(filename, "binary", function(err, file) {  
              if(err) {  
                  response.writeHeader(500, {"Content-Type": "text/plain"});  
                  response.write(err + "\n");  
                  response.end();  
                  return;  
              }  
    
              response.writeHeader(200);  
              response.write(file, "binary");  
              response.end();  
          });  
      });  
  }).listen(8081);  
    
  sys.puts("Server running at http://localhost:8081/"); 


评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。