I have this async function in a file called index.main.js which has a variable , 'targetFiles' which I would like to export to another file which is index.js. Problem is I can't find a way to export the value of this particular variable without getting "undefined" as a result.
I have tried implementing promise, callback , export default function, and doing countless hours of research to no avail.
//this code is in index.main.js
var targetFiles = "";
async function listFilesInDepth()
{
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucketName = 'probizmy';
const [files] = await storage.bucket(bucketName).getFiles();
console.log('List Of Files Available:');
files.forEach(file =>
{
targetFiles = file.name; //this is the variable to export
console.log(`-----`+file.name);
});
return targetFiles;
}
module.exports = {
fn : targetFiles
}
trying to export the value to index.js is either empty or "undefined"
//this is the code in index.js
const a = require('./index.main');
console.log(a.fn); //undefined or empty
The expected value that should be the output is the value of targetFiles. Let's say if targetFiles is abc12345.JSON in the async function,the console.log in index.js should be of that value.
I'm hoping someone could give me some insight on how I could overcome this issue. Thank you in advance :)
Following solution might help you, but not sure for your use case. (Not using
module-exports
):You can use
request-context
package to achieve same functionality.What is package does is, you can set the
value(data)
against akey
and then access the same in the following code execution within the samecontext
.Run
npm install request-context
In your main
app.js
(server file), register therequest-context
as a middleware.And then in your
index.main.js
, oncetargetFiles
is ready, set thetargetFiles
into request context.And in the same request, where you wanna use
targetFile
, you can do the following:index.js
(Can be any file where you needtargetFiles
after being set):Please note: You will be able to access
targetFiles
in the samerequest
you set. That means,request-context
we configured inapp.js
is per API request, meaning, in every API request, you have to set it before reading.Please let me know if the above solution doesn't fit for you.