Is it possible to module.exports a local variable from async function?
Asked Answered
D

1

0

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 :)

Dugaid answered 5/7, 2019 at 1:46 Comment(6)
where did you call the function?Strove
I'm not following by what you mean? This is actually a fragment of the function actually, I just simplified it because my main concern is to export the value of targetFiles to index.js from index.main.js.Dugaid
the reason why its empty is because you need to run the listFilesInDepth() function to have targetFiles's value set.Sulphonamide
Thank you. I've done and I'm able to get the value with a new function with parameter when I use return console.log("The value of targetFiles is "+(newtf)); However when I use return newtf in the function and use console.log(fn.listFilesInDepth()) I get Promise { <pending> } Why is that?Dugaid
Pending mean it's currently in process, you have to wait the return of the promise in order to have the value fulfilled.Terrilynterrine
fn.listFilesInDepth().then(param => console.log(param));Terrilynterrine
A
0

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 a key and then access the same in the following code execution within the same context.

Run npm install request-context

In your main app.js (server file), register the request-context as a middleware.

const contextService = require("request-context");
const app = express();
...
// Multiple contexts are supported, but below we are setting for per request.
app.use(contextService.middleware("request"));
...

And then in your index.main.js, once targetFiles is ready, set the targetFiles into request context.

const contextService = require("request-context");

...
files.forEach(file =>

      {

        targetFiles = file.name;  //this is the variable to export

        console.log(`-----`+file.name);

      });
     // Here `Request` is the namespace(context), targetFileKey is the key and targetFiles is the value.
     contextService.set("request:targetFileKey", targetFiles);
     return targetFiles;

}
...

And in the same request, where you wanna use targetFile, you can do the following:

index.js (Can be any file where you need targetFiles after being set):

const contextService = require("request-context");

...
// Reading from same namespace request to which we had set earlier
const targetFiles = contextService.get("request:targetFileKey");
...

Please note: You will be able to access targetFiles in the same request you set. That means, request-context we configured in app.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.

Aerialist answered 5/7, 2019 at 6:9 Comment(6)
Thank you kindly for your answer. I'm sorry for the late reply as I've been trying to implement your solution, but I don't have an app.js file ,so I created one and used your code, but the value I get from node index.js for targetFiles is returning as undefined. What could I have done wrong?Dugaid
There need not be an index.js file for reading the value. Assume request reaches controller (index.main.js) where we set targetFiles into requestContext, then in the same request, we can access targetFiles anywhere in the code, .ie., assuming the control flows from controller to service file, in service file, you can get targetFiles from requestContextAerialist
Updated the answer with a note and some explanation. Please let me know if you still facing issues. I can share a code example via github, if requiredAerialist
I'm using index.js because that is the file that holds the url to the pdf that I'm basin the system on. targetFile is to declare the name of the pdf file. Index.main.js is for npm, thus index.js is necessary. I tried the requestContext method , however the returning value for some reason is undefinedDugaid
Please check the following repo. Have created a sample code: [email protected]:sagarch888/demouserapp.gitAerialist
Any update. Please let me know if code example has still not solved your issues( or mark the answer as accepted if it did)Aerialist

© 2022 - 2024 — McMap. All rights reserved.