U
U
Umid2016-11-26 20:23:31
Node.js
Umid, 2016-11-26 20:23:31

Fs.exists in node.js?

Good evening.
Started reading Node.js in action book.
Here's the thing:
there is some code (for a complete understanding, the entire code is below):

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

var cache = {};

function send404(res) {
  res.writeHead(404,{'Content-Type':'text/plain'});
  res.write('Error 404: resourse not found');
  res.end();
}

function sendFile(res, filePath, fileContents) {
  res.writeHead(
    200,
    {'content-type':mime.lookup(path.basename(filePath))}
  );
  res.end(fileContents);
}

function serveStatic(res, cache, absPath) {
  if(cache[absPath]) {
    sendFile(res, absPath, cache[absPath]);
  } else {
    fs.exists(absPath, function(exists) {
      if(exists) {
        fs.readFile(absPath, function(err, data) {
          if(err) {
            send404(res);
          } else {
            cache[absPath] = data;
            sendFile(res, absPath, data);
          }
        });
      } else {
        send404(res);
      }
    });
  }
}

var server = http.createServer(function(req, res) {
  var filePath = false;
  
  if(req.url == '/') {
    filePath = 'public/index.html';
  } else {
    filePath = 'public' + req.url;
  }

  var absPath = './' + filePath;
  server.Static(res, cache, absPath);
});

server.listen(3000, function() {
  console.log("Server listening on port 3000");
});

I'm interested in 1 point - the serveStatic function.
On off. The site writes that the fs.exists method has stability-0. And do not recommend using it.
The code is written in this way in the book.
What I want to know:
-What is the fs.exists method for and what is passed as the exists argument here:
fs.exists(absPath, function(exists) {
-More stable alternatives.
- Is it worth using it at all?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dark Hole, 2016-11-26
@DarCKoder

On off. The site writes that the fs.exists method has stability-0. And do not recommend using it.
...and answers, oddly enough, to all your questions. Well, then read the doc, well?
1. It checks for the existence of a file. The function is passed an argument of type boolean(true-false) which, as you might guess, means whether the file exists.
2. Doka says:
Use fs.stat() or fs.access() instead.
3. Depends on node.js version.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question