我在一个名为index.main的文件中有这个异步函数.js它有一个变量,'targetFiles',我想将其导出到另一个文件,即index.js。问题是我找不到一种方法来导出这个特定变量的值而不会因此而"未定义"。
我尝试实现 promise、回调、导出默认函数,并进行了无数小时的研究,但无济于事。
//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
}
尝试将值导出到索引.js为空或"未定义">
//this is the code in index.js
const a = require('./index.main');
console.log(a.fn); //undefined or empty
应作为输出的预期值是目标文件的值。假设目标文件是abc12345。异步函数、控制台中的 JSON .log索引中的 JSON .js 应该是该值。
我希望有人能给我一些关于如何克服这个问题的见解。提前谢谢你:)
以下解决方案可能会对您有所帮助,但不确定您的用例。(不使用module-exports
):
您可以使用request-context
包来实现相同的功能。
包的作用是,您可以针对key
设置value(data)
,然后在同一context
内的以下代码执行中访问相同的。
运行npm install request-context
在主app.js
(服务器文件)中,将request-context
注册为中间件。
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"));
...
然后在您的index.main.js
中,一旦targetFiles
准备就绪,将targetFiles
设置为请求上下文。
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;
}
...
在同一个请求中,您要在其中使用targetFile
,您可以执行以下操作:
index.js
(可以是设置后需要targetFiles
的任何文件):
const contextService = require("request-context");
...
// Reading from same namespace request to which we had set earlier
const targetFiles = contextService.get("request:targetFileKey");
...
请注意: 您将能够以您设置的相同request
访问targetFiles
。这意味着,request-context
我们在app.js
中配置的是每个 API 请求,这意味着在每个 API 请求中,您必须在阅读之前进行设置。
如果上述解决方案不适合您,请告诉我。