2016-04-05 2 views
0

Что нам нужно изменить в следующем коде для добавления в наш путь?Добавить путь к файлу в NODE JS

Наш путь - приложение/публика. Мы хотим, чтобы все файлы в нашей общей папке были основными .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 
    } 
); 

Вот документация Экспресс: http://expressjs.com/