node js localhost shal open a file

Tutorial: I want to open a file via localhost, but I don't know which path I have to type into the Browser. Is localhost, where my server.js is located? (sorry, I'm new to programming and node)

Tutorial-Code

var path = require('path'),
    fs = require('fs');

require('http').createServer(function(req, res) {
  var file = path.normalize(req.url);

  console.log(file);

  path.exists(file, function(exists) {
    if (exists) {
      fs.stat(file, function(err, stat) {
        var rs;

        if (err) { throw err; }
        if (stat.isDirectory()) {
          res.writeHead(403);
          res.end('Forbidden');
        } else {
          rs = fs.createReadStream(file);
          res.writeHead(200);
          rs.pipe(res);
        }
      });
    } else {
      res.writeHead(404);
      res.end('Not found');
    }
  })
}).listen(4000);

request.url is normally /something/like/an/absolute/path unless you get requests from a HTTP proxy client (which adds http://... prefix to request.url) or make some custom HTTP requests.

Anyways path.normalize only takes care of .. And .s. Your code will let anybody access any file (accessible by the account in which node process is running) on your computer.

A better/safer practice is to join __dirname with decoded request.url and check if resolved path starts with the absolute path (with trailing path separator) of the directory you want to serve static content from:

var scriptDir = path.resolve(__dirname + path.sep + "static" + path.sep),
    requestPath = decodeURIComponent(request.url);
requestPath = path.resolve(path.join(__dirname, "static", requestPath));
if (requestPath.indexOf(scriptDir) === 0) {
    // serve the file
} else {
    response.writeHead(403);
    response.end(http.STATUS_CODES[403]);
}

Now if you request say, http://localhost:4000/index.html it should serve the file located in /path/to/your/node/app/dir/static/index.html