Answer the question
In order to leave comments, you need to log in
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");
});
fs.exists(absPath, function(exists) {
Answer the question
In order to leave comments, you need to log in
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?
Use fs.stat() or fs.access() instead.3. Depends on node.js version.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question