creating a password protected zip file using child process in nodejs - linux

I have a very funny issue. I am spawning a child process in nodejs to create a zip password protected file. It is supposed to emulate the following command.
zip -P password -rf finalFileName.zip filePath
here is the code I wrote
function(password, zipName) {
let zip = spawn('zip', ['-P rolemodel','-rj', zipName, this.folderPath ]);
return this;
}
On unzipping the final zip file, I get an invalid password error.
Anything wrong that I am doing here ? I am however able to execute the command on the terminal and get the whole thing to work.

Maybe you can try to put every argument in quotes like following:
zip = spawn('zip',['-P', 'password' , '-rj', 'archive.zip', 'complete path to archive file']);
zip .on('exit', function(code) {
...// Do something with zipfile archive.zip
...// which will be in same location as file/folder given
});

Related

How to delete all files and subdirectories in a directory with Node.js

I am working with node.js and need to empty a folder. I read a lot of deleting files or folders. But I didn't find answers, how to delete all files AND folders in my folder Test, without deleting my folder Test` itself.
I try to find a solution with fs or extra-fs. Happy for some help!
EDIT 1: Hey #Harald, you should use the del library that #ziishaned posted above. Because it's much more clean and scalable. And use my answer to learn how it works under the hood :)
EDIT: 2 (Dec 26 2021): I didn't know that there is a fs method named fs.rm that you can use to accomplish the task with just one line of code.
fs.rm(path_to_delete, { recursive: true }, callback)
// or use the synchronous version
fs.rmSync(path_to_delete, { recursive: true })
The above code is analogous to the linux shell command: rm -r path_to_delete.
We use fs.unlink and fs.rmdir to remove files and empty directories respectively. To check if a path represents a directory we can use fs.stat().
So we've to list all the contents in your test directory and remove them one by one.
By the way, I'll be using the synchronous version of fs methods mentioned above (e.g., fs.readdirSync instead of fs.readdir) to make my code simple. But if you're writing a production application then you should use asynchronous version of all the fs methods. I leave it up to you to read the docs here Node.js v14.18.1 File System documentation.
const fs = require("fs");
const path = require("path");
const DIR_TO_CLEAR = "./trash";
emptyDir(DIR_TO_CLEAR);
function emptyDir(dirPath) {
const dirContents = fs.readdirSync(dirPath); // List dir content
for (const fileOrDirPath of dirContents) {
try {
// Get Full path
const fullPath = path.join(dirPath, fileOrDirPath);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
// It's a sub directory
if (fs.readdirSync(fullPath).length) emptyDir(fullPath);
// If the dir is not empty then remove it's contents too(recursively)
fs.rmdirSync(fullPath);
} else fs.unlinkSync(fullPath); // It's a file
} catch (ex) {
console.error(ex.message);
}
}
}
Feel free to ask me if you don't understand anything in the code above :)
You can use del package to delete files and folder within a directory recursively without deleting the parent directory:
Install the required dependency:
npm install del
Use below code to delete subdirectories or files within Test directory without deleting Test directory itself:
const del = require("del");
del.sync(['Test/**', '!Test']);

Node JS extracting the zip file in winows not working

I am trying to unzip the password protected zip file in window terminal. But I am getting error as
"Error: 'zip' is not recognized as an internal or external command,
operable program or batch file."
var spawn = require('child_process').spawn;
let filePath = "XXX/XX";
let password= "abc";
extractZipWithPassword(filePath, password)
function extractZipWithPassword(filePath, password) {
console.log("Inside here:::::::::::::::::::", filePath);
var dir = spawn('zip',['-P', password, '-j', '-', filePath], {shell:true});
dir.stderr.on('data', (data) => {
console.log('Error: '+data);
return filePath;
})
dir.on('close', (code) => {
console.log("On closing:::::::::::::::")
return filePath;
});
}
zip is not a Powershell built-in construct. You'll want to make use of the Expand-Archive cmdlet.
Expand-Archive -LiteralPath C:\Archives\Draft.Zip -DestinationPath C:\Reference
However, Expand-Archive doesn't work with password protected archives. In my cases though, I've gone with using 7zip to extract these (note that you must first make sure your current working directory is the destination unpack directory):
spawn('7z', ['x', filePath, '-p' + password], { shell: true, cwd: destinationUnpackPath })
A few things to explain above:
-pPASSWORD will have PASSWORD replaced with the actual password. So if your password is "12345", the argument passed would be -p12345.
Note that I added cwd to the spawn options, to make sure the current working directory is set appropriately. 7z x will extract the archive to the cwd.
destinationUnpackPath is not defined in your code above but this should be set to the destination extraction path

nodejs unzip with encoding option

I'm trying to make some code which makes server unzip requested file by using nodejs(express)...
app.post('/unzip', function(req, res) {
//Get User Information
var id = req.body.id;
//Get ZIP Information
var rendering_ready_file_unzip = req.body.filename + '.zip';
var rendering_ready_file_unzip_nonext = req.body.filename;
//Extract zip
var extract = require('extract-zip');
var unzip_route = path.join(__dirname, '../unzip/' + "id" + '/' + date + '/');;
extract(path.join(__dirname, '../upload/' + rendering_ready_file_unzip), {dir: unzip_route}, function (err) {
if (err) {
console.log(err);
}
res.end();
});}
It works... but other languages like Korean damaged after unzip.. So I want to know about unzip-modules which can designate encoding type.
Do you know it?
The problem may not be with the module. It helps to reduce troubled code to the minimum, and in this case that might be the following:
const path = require('path');
const extract = require('extract-zip');
const file_unzip = 'test.zip';
extract(path.join(__dirname, file_unzip), {dir: __dirname}, function (err) {
if (err) {
console.log(err);
}
});
After putting that in index.js and installing extract-unzip, a same-directory test case is possible in bash. Echo Korean characters to a file and make sure they are there:
$echo 안녕하세요>test
$cat test
안녕하세요
Zip the file, remove the original and make sure it is gone:
$zip test.zip test
adding: test (stored 0%)
$rm test
$ls test*
test.zip
Run the script and see that the file has been extracted and contains the same characters:
$node index.js
$ls test*
test test.zip
$cat test
안녕하세요
I got the same results with characters from several other languages. So at least in this setup, the module unzips without changing the characters in the inner files. Try running the same tests on your system, and take a good look at what happens prior to unzipping. Problems could lurk in how the files are generated, encoded, zipped, or uploaded. Investigate one step at a time.

How do I password protect a zip file in Nodejs?

I am creating a zip file using archiver. below is my code to do it. I need to password protect it. How can I do it?
var head={'Content-Type':'application/octet-stream','Content-disposition':'attachment; filename='+zipName,'Transfer-Encoding':'chunked' }
res.writeHead(200,head);
var archive = archiver('zip');
archive.pipe(res);
archive.append(result, { name: attachment.aliasFileName });
archive.finalize();
return res.send("thanks");
If you are working in linux you can do some thing like this
//create a zip
spawn = require('child_process').spawn;
zip = spawn('zip',['-P', 'password' , 'archive.zip', 'complete path to archive file']);
zip .on('exit', function(code) {
...// Do something with zipfile archive.zip
...// which will be in same location as file/folder given
});
Refer https://nodejs.org/api/child_process.html

Node.js fs.unlink function causes EPERM error

I'm using fs.unlink() to delete a file and I receive the following error:
uncaught undefined:
Error: EPERM, Operation not permitted '/Path/To/File'
Anyone know a why this is happening?
You cannot delete a directory that is not empty.
And fs.unlinkSync() is used to delete a file not a folder.
To remove an empty folder, use
fs.rmdir()
to delete a non empty folder, use this snippet:
var deleteFolderRecursive = function(path) {
if( fs.existsSync(path) ) {
fs.readdirSync(path).forEach(function(file) {
var curPath = path + "/" + file;
if(fs.lstatSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};
Snippet from stackoverflow: Is node.js rmdir recursive ? Will it work on non empty directories?
If you want to achieve something like rm -rf does, there is a package from npm called rimraf which makes it very easy.
Maybe the Path of the file is located is erroneus.
if not, try with fs.unlinkSync()
Yes, you don't have permission to delete/unlink that file. Try again with more rights or verify that you're giving it the right path.

Resources