[英]Accessing variable value from index.js to another js file on nodejs
I am new to nodejs and I have index.js
file which is called when I start my nodejs express server using nodemon index command.我是 nodejs 的新手,我有index.js
文件,当我使用 nodemon index 命令启动我的 nodejs express 服务器时会调用该文件。
In this index.js
file I am connecting to google drive and getting jwtClient
object when the connection is successful.在此index.js
文件中,我连接到谷歌驱动器并在连接成功时获取jwtClient
object。
I want to use this jwtClient
object in product.js
file to upload image to google drive.我想在product.js
文件中使用这个jwtClient
object 将图像上传到谷歌驱动器。
In index.js
file once I have value in jwtClient
variable I am doing module.exports = jwtClient;
在index.js
文件中,一旦我在jwtClient
变量中有值,我正在做module.exports = jwtClient;
and I am accessing jwtClient
in product.js
as const jwtClient = require('../index');
我正在访问product.js
中的jwtClient
作为const jwtClient = require('../index');
which is not working.这是行不通的。
What are the ways I can access jwtClient in product.js from index.js without creating new object and having the same object reference.我可以通过哪些方式从 index.js 访问 product.js 中的 jwtClient 而无需创建新的 object 并具有相同的 object 引用。
In index.js file:在 index.js 文件中:
// configure a JWT auth client
let jwtClient = new google.auth.JWT(
privatekey.client_email,
null,
privatekey.private_key,
['https://www.googleapis.com/auth/drive']);
//authenticate request
jwtClient.authorize(function (err, tokens) {
if (err) {
console.log(err);
return;
} else {
console.log("Successfully connected to gdrive!");
}
});
module.exports = jwtClient;
In product.js file在 product.js 文件中
const jwtClient = require('../index');
The problem may be that when you examine your jwtClient
variable, the jwtClient.authorize
did not execute yet.问题可能是当您检查jwtClient
变量时, jwtClient.authorize
尚未执行。 Make sure that in product.js
file you wait till it happen.确保在product.js
文件中等待它发生。 The easyest (but not best) way to do that is最简单(但不是最好)的方法是
const jwtClient = require('../index/jwtClient');
setTimeout(function() {
console.dir(jwtClient);
}, 1000);
The issue was that I was exporting literal instead of Object. So the code module.exports = jwtClient;
问题是我导出的是文字而不是 Object。所以代码module.exports = jwtClient;
exports literal but jwtClient is object so I used exports.jwtClient = jwtClient;
出口文字但 jwtClient 是 object 所以我使用exports.jwtClient = jwtClient;
in index.js
file and then I access it in product.js
file as在index.js
文件中,然后我在product.js
文件中访问它
const index = require('../index.js');
console.log(index.jwtClient);
reference https://www.tutorialsteacher.com/nodejs/nodejs-module-exports参考https://www.tutorialsteacher.com/nodejs/nodejs-module-exports
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.