I am writing a small NodeJS script which takes a zip file and extracts the contents to a folder. I then search the extracted zip contents on the file system for a specified file type which is then output to an array.
The issue I am facing is on the initial run of the script, the extraction process does not complete prior to my "findFile" function kicking off. To resolve this I have attempted to use Async/Await which I was hoping would kick off the "findFile" function upon the successful completion of my unzip/extraction.
Below is a simplified code example:
const fs = require('fs-extra');
const unzipper = require('unzipper');
const path = require('path');
const artifact = 'C:\\PATH\\TO\\MY\\ZIP\\FILE.zip;
const dir = 'C:\\PATH\\TO\\MY\\EXTRACTED\\ZIP\\FILE\\CONTENTS';
const findFile = function (dir, pattern) {
const results = [];
fs.readdirSync(dir).forEach(function (dirInner) {
dirInner = path.resolve(dir, dirInner);
const stat = fs.statSync(dirInner);
if (stat.isDirectory()) {
results = results.concat(findFile(dirInner, pattern));
}
if (stat.isFile() && dirInner.endsWith(pattern)) {
results.push(dirInner);
}
});
return results
}
const readZip = async () => {
fs.createReadStream(artifact).pipe(unzipper.Extract({path: 'C:\\LOCATION\\WHERE\\EXTRACTED\\ZIP\\WILL\\GO'}))
await findFile(dir, ".iar");
}
readZip()
When running the above initially I get the following:
"UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, scandir 'C:\PATH\TO\EXTRACTED\ZIP\CONTENTS'"
However, upon the second run of the code I get the expected results:
[
'C:\\PATH\\TO\\SOME\\FILE.iar',
'C:\\PATH\\TO\\SOME\\FILE.iar',
'C:\\PATH\\TO\\SOME\\FILE.iar'
]
This behavior tells me the "findFile" function executes prior to the extraction process completing. This leads me back to the question:
Question 1: Why is the "findFile" function not using "await" for the extract process to complete before executing?
Question 2: Can anyone provide me with some code examples of how I can make this happen while still utilizing the code I have already written?
I would prefer to not have to rewrite the entirety of this script as I am relatively sure this is a syntactical issue on my part and since I am a newb at this rewriting the entirety of the script would take me quite some time to get completed. Any and all help is appreciated....