2017-02-27 93 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给出了当前脚本文件的目录。