Rayn D Rayn D - 27 days ago 6
Node.js Question

How to call to function with parameter from event

I use the following code which is working:

yauzl.open(filePath, function (err, zipFile) {
zipFile.on('entry', (entry) =>{
//console.log(entry.fileName);
if (/\/$/.test(entry.fileName)) {
return;
}
zipFile.openReadStream(entry, (err, readStream) => {
if (err) {
logger.info(err);
reject(err);
} else {
...


Now I want to change the code a bit to make it more readable by doing something like the following:

yauzl.open(filePath, (err, zipFile) => {
//zipFile = zipFile;
if (err) {
__rejectAndLog(err);
return;
}

zipFile.on('entry', __processEntry(zipFile))
.once('error', __rejectAndLog)
.once('close', () => {
console.log(`Unpacked ${numOfFiles} files`);
resolve();
});
});


This is the processEntry:

function __processEntry(zipFile) {

zipFile.openReadStream(entry, (err, readStream) => {
if (err) {
__rejectAndLog(err);
return;
}

if (/\/$/.test(entry.fileName)) {
// directory file names end with '/'
return;
}


Here I got the error
cannot use **openReadStream** of undefined
. How can I handle it?

zipFile.openReadStream(entry, (err, readStream) => {


In addition I need to pass also the entry
value
any idea?

Answer

Use bind zipFile.on('entry', __processEntry.bind(null, zipFile)) and re-declare your __processEntry as function __processEntry(zipFile, entry)