[英]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/SurajDayal/Documents/ass2/app.js并转到http:// localhost:2405 /时 ,终端给出了错误...。
events.js:160 throw er; //未处理的“错误”事件^
错误:ENOENT:没有此类文件或目录,请在错误(本机)处打开“ ./index.html”
目录结构:
采用
var path = require('path');
fs.createReadStream(path.join(__dirname, "index.html")
您的版本不起作用,因为相对路径是相对于当前工作目录(启动节点时控制台中的当前目录)的,而不是相对于脚本文件的。
__dirname
给出当前脚本文件的目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.