Node - Check to see if a directory exists - node.js

This should be a fairly simple one to answer I would hope, however it's got me stumped - maybe I've been staring at too much code today!
I am trying to do a simple if statement which checks to see if a folder exists. If the folder doesn't exist, make it, if it does, delete the content.
The problem I am having is that if the directory doesn't exist, then the callback (stats) is undefined. With fs.exist it would be quite simple, but since its deprecated, I wanted to ensure this was future proofed.
var seriesid = 5;
fs.stat("temp/" + seriesid, function (err, stats){
if(!stats.isDirectory()){
fs.mkdir("temp/" + seriesid);
console.log('Folder doesn\'t exist, so I made the folder ' + seriesid);
callback();
}
else if (err != 'ENOENT') {
callback(err);
}
else {
// TODO: Folder exists, delete contents
console.log('Does exist');
callback();
}
});
Any help on how to accomplish this would be appreciated

Check err first. Then check isDirectory()
fs.stat("temp/" + seriesid, function (err, stats){
if (err) {
// Directory doesn't exist or something.
console.log('Folder doesn\'t exist, so I made the folder ' + seriesid);
return fs.mkdir("temp/" + seriesid, callback);
}
if (!stats.isDirectory()) {
// This isn't a directory!
callback(new Error('temp is not a directory!'));
} else {
console.log('Does exist');
callback();
}
});

you need to check if stats exist before doing !stats.isDirectory()

Related

Write a file into specific folder in node js?

Would like to write data into specific folder using writefile in node js.
I have seen couple of questions in stackoverflow regarding this but none of them worked for me .
For example :
fs.writeFile('./niktoResults/result.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Results Received');
});
This throws an error "NO SUCH FILE OR DIRECTORY"
Is there any alternative for writing data into specific folder node js ???
Ensure that the directory is available & accessible in the working directory.
In this case, a function like below needs to be called at the start of the application.
function initialize() {
const exists = fs.existsSync('./niktoResults');
if(exists === true) {
return;
}
fs.mkdirSync('./niktoResults')
}
Error caused by directory not existing, create a directory if it does not exist.
function create(text, directory, filename)
{
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
console.log('Directory created');
create(text, directory);
} else {
fs.writeFile(`${directory}/${filename}`, `${text}`, function (error) {
if (error) {
throw error;
} else {
console.log('File created');
}
});
}
}
create('Text', 'directory', 'filename.txt');

Check for req.files object empty

I am uploading file through express-fileupload. My file gets uploaded successfully if I am not checking for req.files as empty. But I am getting one error as when I am going to check for req.files as empty. I am posting my code as referenace.
if(req.files.length > 0){
console.log('file is exist');
var file_name = req.files.filetoupload;
file_name.mv("public/uploads/"+ file_name.name, function(err){
if(err){
console.log(err);
var profile_pic_name = '';
} else {
var profile_pic_name = file_name.name;
}
});
}
else
{
console.log('file not exist');
var profile_pic_name = '';
}
So when I am trying to upload a file it goes in else section and prints "file not exist" on console. So my main concern is how to check if req.files is empty or not.
Thanks in advance
Sorry I don't know if I understood correctly your question.
Try something like that:
req.files && req.files.length
I hope this help, If this doesn't meet your necessity let me know
You can easily achieve that using a conditional ternary operator.
For instance, below sample code print "Non Empty File" if req.files exists or "Empty file" if req.files is empty.
req.files ? console.log('Non Empty File') : console.log('Empty file');
You can do something like this and find out if the file exists or not.
if (!req.files) {
// File does not exist.
console.log("No file");
} else {
// File exists.
console.log("File exists");
}
try {
var file_name = req.files.filetoupload;
file_name.mv("public/uploads/"+ file_name.name)
} catch (error) {
res.send(`File not found`)
}
Use the try and catch method and it works...

Fast async way to check if file existin nodejs

I have used the following async method to check if file exists:
var fs = require('fs');
module.exports.exists = function(path, cb) {
fs.stat(require('path').join(__dirname, '../public', path), function(err, stat) {
if (err == null) {
console.log('File exists :' + path);
cb(true);
} else if (err.code == 'ENOENT') {
//file does not exist
console.log('No file: ' + path);
cb(false);
} else {
console.log('Some other error: ', err.code);
cb(false);
}
});
}
If file exists, i redirect to the file in pathStr. If not, display that resource does not exist. Although this is asynchronous, i notice that the web server is much slower and accepts fewer requests with this fs.stat method(if this is commented out, the performance is significantly better). Is there a way in node.js to speed up file exists or not check asynchronously ?

How to guarantee non-existance of a file before creating?

fs.exists is now deprecated for a decent reason that I should try to open a file and catch error to be sure nothing is possible to delete the file in between checking and opening. But if I need to create a new file instead of opening an existing file, how do I guarantee that there is no file before I try to create it?
You can't. You can however, create a new file or open an existing one if it exists:
fs.open("/path", "a+", function(err, data){ // open for reading and appending
if(err) return handleError(err);
// work with file here, if file does not exist it will be created
});
Alternatively, open it with "ax+" which will error if it already exists, letting you handle the error.
module.exports = fs.existsSync || function existsSync(filePath){
try{
fs.statSync(filePath);
}catch(err){
if(err.code == 'ENOENT') return false;
}
return true;
};
https://gist.github.com/FGRibreau/3323836
https://stackoverflow.com/a/31545073/2435443
fs = require('fs') ;
var path = 'sth' ;
fs.stat(path, function(err, stat) {
if (err) {
if ('ENOENT' == err.code) {
//file did'nt exist so for example send 404 to client
} else {
//it is a server error so for example send 500 to client
}
} else {
//every thing was ok so for example you can read it and send it to client
}
} );

Using findOne then save() to replace a document, mongoose

I want to use the validation in my schema. Therefore i can't use findOneAndUpdate (?). I must use save.
Problem is, if I use findOne, then replaces the object with the one I'm going to replace it with, it will no longer have the save function.
mongoose.model('calculations').findOne({calcId:req.params['calcId']}, function(err, calculation){
if(err) {errHandler.serverErr(err, res, 'Something went wrong when trying to update a calculation'); return;}
calculation = calculationToReplace;
calculation.save(function(err, calc){ //No longer exists
if(err) {errHandler.serverErr(err, res, 'Something went wrong when trying to update a calculation'); return;}
res.send(200);
});
});
This must be a common task but I can't find any solution. How do I fix this?
There is a simple solution to your (by now really old) question.
In my case I had to have a findOneAndUpdate upsert that returned more information on what happened. So my solution was to step through the process to update the object with a for loop.
(Think the reason why you can't just copy is that the doc object contains a bunch of "extras" like version information and save function and other "bits"); So here is my solution.
exports.postData = function(req,res) {
console.log("will create " + req.body.alias);
console.log("It is level " + req.body.level); //OK, all this have to be changed to members of the data! req.body contains all the data sent from the user at this time
var query = { 'fulltext' : req.body.fulltext};
console.log("Checkking if " + req.body.fulltext + " exists")
Skill.findOne(query, function (err,doc){
if(err) return res.status(500).send(err)
if (!doc){
console.log(req.body.fulltext + " not found!")
var newdoc = new Skill(req.body);
newdoc.save(function(err){
if(err) return res.status(500).send(err)
console.log(newdoc.fulltext + " created as " + newdoc._id);
return res.status(200).send({_id: newdoc._id, alias: newdoc.alias})
})
return res.status(200).send('blal')
} else {
console.log(req.body.fulltext + " found!")
for (var id in req.body ){
doc[id]= req.body[id];
}
doc.save( function(err){
if(err) return res.status(500).send(err)
return res.status(200).send({_id: doc._id, alias: doc.alias})
})
//return res.status(200).send({_id: doc._id, alias: doc.alias})
}
I have not tested the following, so I am not sure if this works properly but it should probably be fine:
Swap this:
calculation = calculationToReplace;
with this:
for (var key in calculationToReplace)
if(typeof calculation[key] !== 'function')
calculation[key] = calculationToReplace[key];
Yes there is a way. You can read the mongoose documentation here. Take a look at the following code.
Tank.findById(id, function (err, tank) {
if (err) return handleError(err);
tank.size = 'large';
tank.save(function (err) {
if (err) return handleError(err);
res.send(tank);
});
});
This approach involves first retreiving the document from Mongo, then issuing an update command (triggered by calling save).

Resources