2017-02-27 94 views
0

這裏是我的Javascript代碼的JavaScript服務器...運行HTML與node.js的

var http = require ('http'); 
var fs = require('fs'); 

var port = '2405'; 

function send404Response(response){ 
    response.writeHead(404, {"Content_Type": "text/plain"}); 
    response.write("Error 404: Page not found!"); 
    response.end(); 
} 

function onRequest(request,response){ 
    if(request.method == 'GET' && request.url == '/'){ 
    response.writeHead(200, {"Content-Type": "text/html"}); 
    fs.createReadStream("./index.html").pipe(response); 
    } else{ 
    send404Response(response); 
    } 
} 

http.createServer(onRequest).listen(port); 
console.log("Server is now running..."); 

當我寫在終端節點/Users/Sur​​ajDayal/Documents/ass2/app.js並轉到http://localhost:2405/的終端提供錯誤....

events.js:160 throw er; // Unhandled 'error' event ^

Error: ENOENT: no such file or directory, open './index.html' at Error (native)

目錄結構:

Folder Layout

+0

[NodeJS訪問具有相對路徑的文件]的可能重複(http://stackoverflow.com/questions/32705219/nodejs-accessing-file-with-relative-path) – NineBerry

回答

1

你可能從另一個目錄開始你的應用程序。這裏的相對路徑./index.html將相對於當前的工作目錄。

如果你想去相對於當前正在運行的文件,請嘗試__dirname

fs.createReadStream(__dirname + '/index.html').pipe(response); 

另外,如果你需要做任何事情更加複雜的HTTP服務,請Express。有一個很好的靜態文件模塊,但它也是一個很好的工具,用於HTTP應用程序所需的路由和其他常用功能。

0

使用

var path = require('path'); 
fs.createReadStream(path.join(__dirname, "index.html") 

您的版本不工作,因爲(當你開始節點在控制檯當前目錄)的相對路徑是相對於當前的工作目錄,而不是相對於腳本文件。

__dirname給出了當前腳本文件的目錄。