Node zip-folder Path error - node.js

So my project structure looks like:
root
app.js
node_modules
package.json
Spreadsheets
I want to use the zip-folder module to zip the contents of the folder spreadsheets. The code provided is:
var zipFolder = require('zip-folder');
zipFolder('/path/to/the/folder', '/path/to/archive.zip', function(err) {
if(err) {
console.log('oh no!', err);
} else {
console.log('EXCELLENT');
}
});
My code is:
zipFolder('./Spreadsheets/', './', function(err) {
if (err) {
console.log('oh no!', err);
} else {
console.log('EXCELLENT');
}
});
because I want to save the zip in the root folder. However I get the following error:
Error: EISDIR: illegal operation on a directory, open './'
at Error (native)
I believe this has something to do with paths but am not sure how to proceed.

You missed zip file name. Working code looks like this:
zipFolder('./Spreadsheets/', './Spreadsheets.zip', function(err) {
if (err) {
console.log('oh no!', err);
} else {
console.log('EXCELLENT');
}
});
PS Welcome to Stack Overflow!

Related

How to set parameters to zip a folder in nodejs

I want zip a folder which contains few files. I am using zip-folder and 7zip-min modules they are working fine. But, I would like to add some parameters to it, like compression level and directory size and so on.
If it is not possible with this module, Can anyone provide other suggestions?
Here is my code :
Example 1-
const zipFolder = require('zip-folder');
zipFolder('./folder', './compressed.zip', function(err) {
if(err) {
console.log('something went wrong!', err);
} else {
console.log('done with compressing');
}
});
Example 2-
const _7z = require('7zip-min');
let pack = _7z.pack('./folder', './compressed.7z', err => {
console.log('I am done with compressing')
});

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

node js file systems read a dynamically changing path to a pdf

I am trying to read a pdf file from fs and send it through email using sendgrid.
My folder structure is like this
/
-src
--controllers
---travelplan.js
-pdf
In the travelplan.js if I do it like this
fs.readFile('pdf/204.pdf', function (err, data) {
if (err) {
console.log("THIS ERROR IS AWESOME", err)
}
})
everything works fine. No problem.
But if read it like this
let pdf_number = 204;
fs.readFile(`pdf/${pdf_number}.pdf`, function (err, data) {
if (err) {
console.log("THIS ERROR IS AWESOME", err)
}
})
This doesn't work. Pdf doesn't send correctly.
Then I tried this
let pdf_number = 204;
var pdf_path = path.join(__dirname, '..', 'pdf',pdf_number);
fs.readFile(pdf_path, function (err, data) {
if (err) {
console.log("THIS ERROR IS AWESOME", err)
}
})
This also doesn't work.
How do I read a pdf file by passing the pdf file name as an argument?

EBUSY error when deleting a file using unlink

I have a delete route which deletes an image file. Following is the code:
router.delete('/:id', (req, res) => {
let pathForThumb = '';
let pathForImage = '';
Image.findOne({ _id: req.params.id })
.then(getImage => {
pathForThumb = getImage.thumbPath;
pathForImage = getImage.imagePath;
getImage.remove();
})
.then(removeThumb => {
fs.unlink(pathForThumb, (err) => {
if (err) {
req.flash('error_msg', 'There was an error deleting the thumbnail');
res.redirect('/user/userdashboard');
}
});
})
.then(removeMainImage => {
fs.unlink(pathForImage, (err) => {
if (err) {
console.log(err);
req.flash('error_msg', 'There was an error deleting the main image');
res.redirect('/user/userdashboard');
} else {
req.flash('success_msg', 'Image removed');
res.redirect('/user/userdashboard');
}
});
})
.catch(err => {
console.log(err);
});
});
as you can see when I upload a file I store it's path and also generate a thumbnail in the /uploads/thumbs/ folder and store the path of the thumb nail as well. In the above code I first get the image using findOne, store the paths of both images in variables and then call fs.unlink in a promise. What is happening is that my thumbnail gets deleted but I am getting the following error in the removeMainImage then condition:
{ Error: EBUSY: resource busy or locked, unlink 'C:\Users\Amin Baig\Desktop\Teaching\galleryprj\public\uploads\XC6kPqWf9_dphaBmUG__I7SN7PAEl_1531823330941_CEI21.jpg'
errno: -4082,
code: 'EBUSY',
syscall: 'unlink',
path: 'C:\\Users\\Amin Baig\\Desktop\\Teaching\\galleryprj\\public\\uploads\\XC6kPqWf9_dphaBmUG__I7SN7PAEl_1531823330941_CEI21.jpg' }
I am using windows 10 for my dev environment os.
Have been trying to find a solution for this, please help.
In my experience, Windows behaves unpredictable when it comes to file locks. In my projects I fixed errors like this by retrying until it works.
Here's some example code:
/**
* On windows, the file lock behaves unpredictable. Often it claims a databsae file is locked / busy, although
* the file stream is already closed.
*
* The only way to handle this reliably is to retry deletion until it works.
*/
const deleteFile = async (filePath) => {
try {
await unlink(filePath);
} catch (err) {
unlinkRetries--;
if (unlinkRetries > 0) {
await deleteFile();
} else {
throw err;
}
}
}

Nodejs return console.log('...')?

I was looking at how to write files in node, and I found this block of code:
var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
Now, inside the if(err){} block, where is this console.log(err) being returned to? How does the error handling work in node?
It is essentially doing nothing but breaking the logic chain of the callback.
Error handing in node is mainly callback based like you see here.
For example:
var fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if (err) {
/* Handle error appropriately */
} else {
/* Code that relies on /tmp/test to exist. */
}
});
So basically, you are saying to fs.writeFile that when it is finished to call a function
function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
}
Normally the callbacks do not care about what you return, So the return in case of error that you write there means that the code does not proceed, so that the second console.log is not printed.

Resources