当前位置: 代码迷 >> JavaScript >> node.js 读取资料
  详细解决方案

node.js 读取资料

热度:375   发布时间:2012-10-30 16:13:36.0
node.js 读取文件
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/"); 

  相关解决方案