簡體   English   中英

使用node.js在javascript服務器中運行html

[英]running html in javascript server with node.js

這是我的Javascript代碼...

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; //未處理的“錯誤”事件^

錯誤:ENOENT:沒有此類文件或目錄,請在錯誤(本機)處打開“ ./index.html”

目錄結構:

文件夾布局

您可能正在從另一個目錄啟動應用程序。 ./index.html的相對路徑將相對於當前工作目錄。

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

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

另外,如果您需要為HTTP服務做更多復雜的事情,請查看Express 有一個不錯的靜態文件模塊,但它也是一個不錯的實用程序,用於路由和HTTP應用程序所需的其他常用功能。

采用

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

您的版本不起作用,因為相對路徑是相對於當前工作目錄(啟動節點時控制台中的當前目錄)的,而不是相對於腳本文件的。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM