繁体   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