[英]node.js, socket.io, __dirname routing issue
I am a complete noob to node, so the solution to this might be obvious, and perhaps I am just not grasping some main concepts here. 我对节点完全陌生,因此解决方案可能很明显,也许我只是在这里没有掌握一些主要概念。 Trying to create a simple route to read a file with node.js and socket.io.
尝试创建一个简单的路由来使用node.js和socket.io读取文件。
var http = require("http");
var url = require('url'); // is used to to parse interpret and manipulate urls
var fs = require('fs'); // is used to handle files, you can read about it here.
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname; //.replace(/^\//,""); // socket.html
console.log("path: " + path);
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
break;
case '/socket.html':
console.log("case: " + path);
console.log("__dirname: " + __dirname);
console.log("full path: " + __dirname + path);
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("socket: opps this doesn't exist - 404");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, "utf8");
}
});
break;
default:
response.writeHead(404);
response.write("Default: opps this doesn't exist - 404");
break;
}
response.end();
});
server.listen(8002);
When I console.log(__dirname and path) I am getting "C:\\wamp\\www\\panel\\test\\try2/socket.html" 当我console.log(__ dirname和路径)时,我得到“ C:\\ wamp \\ www \\ panel \\ test \\ try2 / socket.html”
I am aware that I have a \\ or a / problem, I guess my question here is, Since this is running on a node server should'nt __dirname be all "/" instead? 我知道我有一个\\或/问题,我想这里的问题是,由于这是在节点服务器上运行,因此__dirname不应全部为“ /”吗? the expected result I thought it would print would be " http://localhost:8002/socket.html "
我认为它将打印的预期结果是“ http:// localhost:8002 / socket.html ”
Any help in guidance of explanation of what is going on here would help. 指导此处发生的情况的任何帮助都将有所帮助。
__dirname
refers to the physical path of the directory containing the script you're executing on the machine. __dirname
指目录的物理路径,其中包含您正在计算机上执行的脚本。 In your case you're running your server script from C:\\wamp\\www\\panel\\test 您的情况是从C:\\ wamp \\ www \\ panel \\ test运行服务器脚本
To get the HTTP path, you'll need to use request.url
要获取HTTP路径,您需要使用
request.url
Since this is running on a node server should'nt __dirname be all "/" instead?
由于这是在节点服务器上运行,因此__dirname应该不是全“ /”吗?
It's running on your local machine running Windows, so it uses Windows' \\
. 它运行在运行Windows的本地计算机上,因此使用Windows的
\\
。 The __dirname
on a Unix based OS will return the path with forward slashes instead. 在基于Unix的操作系统上,
__dirname
将返回带正斜杠的路径。
As @Derek pointed out, it returns the path to the current directory, not to the current URL. 正如@Derek指出的那样,它将返回当前目录的路径,而不是当前URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.