-->

Is it possible to module.exports a local variable

2019-08-21 12:20发布

问题:

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

回答1:

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.