Node JS extracting the zip file in winows not working - node.js

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

Related

Running a Powershell script from a node program in a GitHub action

Well, yes, that's a thing. After trying to run the PS script directly and failing, let's try the roundabout way of running it from a node script, which are legit in the GitHub actions environment. So after many attempts, here's my last one (taken from this answer:
var spawn = require("child_process").spawn,child;
var workspace = process.env.GITHUB_WORKSPACE;
var file = workspace + "\\upgrade.ps1";
console.log( "Workspace ", workspace, " file ", file );
child = spawn("powershell.exe",[ file ]); // more stuff to print output after this
This fails with:
Workspace d:\a\rakudo-star-fix-action\rakudo-star-fix-action file d:\a\rakudo-star-fix-action\rakudo-star-fix-action\upgrade.ps1
Powershell Errors: d:\a\rakudo-star-fix-action\rakudo-star-fix-action\upgrade.ps1 : The term
Powershell Errors: 'd:\a\rakudo-star-fix-action\rakudo-star-fix-action\upgrade.ps1' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is
correct and try again.
At line:1 char:1
+ d:\a\rakudo-star-fix-action\rakudo-star-fix-action\upgrade.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (d:\a\rakudo-sta...ion\upgrade.ps1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Powershell Script finished
And I really have no idea what's happening here. The node script and the PS script are in the same directory, root directory of the repository, which should be available under that environment variable.
The workspace is actually different from the location of your files in your repo.
In nodejs, you can write the following to get your current working directory and its files:
const directoryPath = __dirname;
console.log(directoryPath);
fs.readdir(directoryPath, function(err, files) {
if (err) {
console.log("Error getting directory information.")
console.log(err)
} else {
files.forEach(function(file) {
console.log(file)
})
}
})
You can then specify a const variable const directoryPath = __dirname; and then concatenate it in your var file:
const directoryPath = __dirname;
var spawn = require("child_process").spawn,child;
var file = directoryPath + "\\upgrade.ps1";
child = spawn("powershell.exe",["-NoProfile", "-File", file ])
The powershell script should run from there.
EDIT:
I just tested this on a test repo here

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 to pass parameters from exec method to batch file using NodeJS

I am creating a child process in nodejs where it will compile and execute the java code. Below is the code
const exec = require('child_process').exec;
exec('C:/Development/vilearn/vilearn_node/src/my.bat', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
How can i pass the parameters from exec method to batch file.
Below is my batch file.
set path=C:\Program Files\Java\jdk1.8.0_111\bin
cd C:\Development\vilearn\vilearn_node\src
pwd
javac Hello.java
java Hello
As you can see from the above code i am using this batch file to compile the java code. Here i want to pass the path where java file exists and also the name of the java file from exec method so that it will b dynamic.
Please guide me
Help Appreciated!
Use ‘%*’ to select all parameters or ‘%1’, ‘%2’, ... to select a specific one
And use ‘spawn’ to load the batch then pass the params on the second param as an array of strings
You may pass parameters from the nodejs script like this,
const exec = require('child_process').exec;
const param1 = 'Hello.java';
const param2 = 'Hello';
exec(`"C:/Development/vilearn/vilearn_node/src/my.bat" "${param1}" "${param2}"`, (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
in your bat file,
set path=C:\Program Files\Java\jdk1.8.0_111\bin
cd C:\Development\vilearn\vilearn_node\src
pwd
javac %1
java %2
Use double quotes on your parameters to avoid splinting from space as 2 parameters

creating a password protected zip file using child process in nodejs

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

Trying to exec svn ls command in a nodejs child process returning error

I want to run an svn ls <path> command when I try it out I get an error stating
svn: '.' is not a working copy
svn: Can't open file '.svn/entries': No such file or directory
which is the standard error you would get for trying to run the command without a path and in a directory that is not version controlled by SVN. But the thing is when I console.log my command before executing it it specifically states the full, valid, path to a remote SVN repository.
e.g., svn ls https://svn.example.com/this/is/a/valid/repo
If I copy and paste the log into my own bash it lists the directory just fine.
Here's the code I'm tyring to execute
function svnls (path) {
var cp = require('child_process'),
command = 'svn ls ' + path;
console.log(command); // -> svn ls https://svn.example.com/this/is/a/valid/repo
cp.exec(command, function (err, stdout, stderr) {
console.log(stderr);
});
}
Alternatively I've tried the more verbose method of spawning a bash instance:
function svnls (path) {
var bash = require('child_process').spawn('bash');
bash.stdout.on('data', function (data) {
var buff = new Buffer(data),
result = buff.toString('utf8');
console.log(result);
});
bash.stderr.on('data', function (data) {
var buff = new Buffer(data),
error = buff.toString('utf8');
console.log(error);
});
bash.on('exit', function (code) {
console.log(code);
});
bash.stdin.write('svn ls ' + path);
bash.stdin.end();
}
and it outputs the same error to console as well as the exit code (1).
Does anyone know why this is failing?

Resources