Setting scope of a required module?

Hi all,

I’m writing an app where I allow users to upload some files.]

I have a file A which looks like this:

//A.js
const fs = require('fs');
const imageHelper = require('./B.js');

//upload function
if (folderExists){
   imageHelper.moveFileAndSend(fs, oldName, newFileLocation, userData, res);
                
} else {
   fs.mkdirSync(newDirectoryPath);
   imageHelper.moveFileAndSend(fs, oldName, newFileLocation, userData, res);
 }


//B.js

function moveFileAndSend(fs, oldPath, newPath, userData, res){
    //moves an image file to path and sends responseObj to be handled by client
    fs.rename(oldPath, newPath, () => {
        res.send(responseObj);
    });
}

module.exports = {
    moveFileAndSend: moveFileAndSend
}

However, what I don’t like about this is in A.js when i call imageHelper.moveFileAndSend() I have to pass in fs (defined as a requirement at start of file) and res (which is from the respone obj from express) to the function as arguments

I dont think i will be able to get around passing res as an argument because it only lives in that specific express route. However, can I not somehow pass fs into the functions scope when I require it, so I do not have to pass it in as an argument?

Thanks all

Yes, I believe you will have to pass res to B.js. I’m not sure why you would have to pass fs though. Just require it at the top of B.js the same way you did in A.js

Hi @faktotum85,

You are right in that requiring fs at the top of B.js will work. I wonder though, is requiring it in both A.js and B.js inefficient? Or is it the code still only pulled in once, cached, and then can be used in both files?

Thanks!

Node only pulls the code in once, so it’s not an issue.

1 Like