2016-04-05 167 views
0

我們需要在下面的代碼中編輯以添加到我們的路徑中?在NODE JS中添加文件路徑

我們的路徑是app/public。我們希望能夠將公共文件夾中的所有文件都作爲主要的.html文件。我是新來的,任何幫助將不勝感激! 非常感謝!

var http = require("http"), 
url = require("url"), 
path = require("path"), 
fs = require("fs") 
port = process.argv[2] || 8888; 

http.createServer(function(request, response) { 

var uri = url.parse(request.url).pathname 
, filename = path.join(process.cwd(), uri); 

path.exists(filename, function(exists) { 
if(!exists) { 
    response.writeHead(404, {"Content-Type": "text/plain"}); 
    response.write("404 Not Found\n"); 
    response.end(); 
    return; 
} 

if (fs.statSync(filename).isDirectory()) filename += '/index.html'; 

fs.readFile(filename, "binary", function(err, file) { 
    if(err) {   
    response.writeHead(500, {"Content-Type": "text/plain"}); 
    response.write(err + "\n"); 
    response.end(); 
    return; 
    } 

    response.writeHead(200); 
    response.write(file, "binary"); 
    response.end(); 
}); 
}); 
}).listen(parseInt(port, 10)); 

console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown"); 
+0

爲什麼-1我的答案? – VirginieLGB

回答

-1

我建議你嘗試使用express,使之更容易處理,特別是在未來爲您的應用程序變得更大。

var express = require('express'); 
var app = express(); 
var cookieParser = require('cookie-parser'); // might be useful. Not required though 

app.set('port' , process.argv[2] || 8888); 
app.use(express.static('./public')).use(cookieParser()); // sets path to your public folder 

// you can add some more configuration here 

// then finally start your server 
http.createServer(app).listen( 
    app.get('port') , 
    function() { 
     console.log('Express server listening on http port ' + app 
       .get('port')); 
     // here, complete with your callback 
    } 
); 

下面是Express文檔:http://expressjs.com/