0

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.

    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"

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? the expected result I thought it would print would be "http://localhost:8002/socket.html"

Any help in guidance of explanation of what is going on here would help.

2 Answers 2

2

__dirname refers to the physical path of the directory containing the script you're executing on the machine. In your case you're running your server script from C:\wamp\www\panel\test

To get the HTTP path, you'll need to use request.url

Sign up to request clarification or add additional context in comments.

Comments

0

Since this is running on a node server should'nt __dirname be all "/" instead?

It's running on your local machine running Windows, so it uses Windows' \. The __dirname on a Unix based OS will return the path with forward slashes instead.

As @Derek pointed out, it returns the path to the current directory, not to the current URL.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.