Check for req.files object empty - node.js

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...

Related

Node - Check to see if a directory exists

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()

NWJS can't re-save file

I have nwjs app, and i want save file. So I have code like this:
try {
fs.writeFileSync(this.value, data);
} catch (e) {
alert(e);
}
and it's good. But when I want re-save data in the same file, it's not working. No error but no new data in file to.
You should refer this documentation.
Try below code.
var fs = require('fs');
fs.writeFile("/tmp/test", "Hello!", function(e) {
if(e) {
return console.log(e);
}
console.log("The file is saved!");
});
This link will be useful too :)
Hope it will help you :)
I have an input like <input type="file" nwsaveas="myFile.txt"> and can't re-save file because of this issue:
https://github.com/nwjs/nw.js/wiki/file-dialogs#choosing-the-same-directory-multiple-times
To solve it I reset the input value to empty string after fs.writeFile().

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
}
} );

How to unlink a file in node.js while there is an error on it?

I have a .zip file, I want to extract it, but this file has a problem that it cannot be extracted. When that error is emitted, I want to delete(unlike) .zip file but I cannot do that. This is the code:
var unzipExtractor = unzip.Extract({ path: dir });
var source = fs.createReadStream(dir + 'sub.zip');
var unZip = source.pipe(unzipExtractor);
unZip.on('error', function(err) {
fs.unlink(dir + 'sub.zip', function(err){
if (err) console.log(err); else console.log('File extracted !');
})
})
"File extracted !" is printed out, but the file sub.zip is not deleted.Can onyone help me out?
Thanks advance for any help!

Different results from asynchronous and synchronous reading

I have a fairly simple script that attempts to read and then parse a JSON file. The JSON is very simple and I am pretty sure it is valid.
{
"foo": "bar"
}
Now, I have been trying to read it with fs.readFile. When read no errors occur and the returned data is a string. The only problem is that the string is empty.
I repeated my code but used fs.readFileSync, this returned the file perfectly using the same path. Both had a utf-8 encoding specified.
It is very simple code, as you can see.
fs.readFile('./some/path/file.json', 'utf8', function(err, data) {
if(!err) {
console.log(data); // Empty string...
}
});
console.log(fs.readFileSync('./some/path/file.json', 'utf8')); // Displays JSON file
Could it be permissions or ownership? I have tried a permission set of 755 and 777 to no avail.
I am running node v0.4.10. Any suggestions to point me in the right direction will be much appreciated. Thanks.
Edit: Here is a block of my actual code. Hopefully this will give you a better idea.
// Make sure the file is okay
fs.stat(file, function(err, stats) {
if(!err && stats.isFile()) {
// It is okay. Now load the file
fs.readFile(file, 'utf-8', function(readErr, data) {
if(!readErr && data) {
// File loaded!
// Now attempt to parse the config
try {
parsedConfig = JSON.parse(data);
self.mergeConfig(parsedConfig);
// The config was loaded and merged
// We can now call the callback
// Pass the error as null
callback.call(self, null);
// Share the news about the new config
self.emit('configLoaded', file, parsedConfig, data);
}
catch(e) {
callback.call(self, new Error(file + ': The config file is not valid JSON.'));
}
}
else {
callback.call(self, new Error(file + ': The config file could not be read.'));
}
});
}
else {
callback.call(self, new Error(file + ': The config file does not exist.'));
}
});
This is pretty weird.
The code looks.
var fs = require('fs');
fs.readFile('./jsonfile', 'utf8', function(err, data) {
if(err) {
console.error(err);
} else {
console.log(data);
parsedConfig = JSON.parse(data);
console.log(parsedConfig);
console.log(parsedConfig.foo);
}
});
Json file:
{
"foo": "bar"
}
output :
$ node test_node3.js
{
"foo": "bar"
}
{ foo: 'bar' }
bar
This is on node 0.4.10 , but i'm pretty sure it should work on all node version.
So why your data is empty ? You should check err in this case (like mine) and post the output if any. If you have no error, you may fill a bug on github

Resources