如何访问节点js中另一个文件中的变量
我有2个文件:export.js和server.js
我正在尝试访问server.js中export.js中的变量,但我得到了未定义。
请注意,我正在使用knexjs,我给它命名为'db';
export.js
let count;
const livePending = (db) => {
db('cart')
.count('id').where('status','=','Pending')
.then(data => {
if (data[0]) {
count = data[0].count;
}
}).catch(err => res.status(400).send('DB Connection failed!'));
}
module.exports = {
livePending: livePending,
pCount: count
}
server.js
[...]
const anotherFile = require('./export');
anotherFile.livePending(db);
console.log(import.pCount);
当我尝试在export.js中的livePending函数中控制日志时,我得到所需的计数,即1。
我这样做的原因是为了减少server.js中的代码行。如果我在server.js中执行完全相同的功能,我会得到正确的结果。
回答如下:我创建了一个小节点应用程序来测试代码的变体。两个重要发现:
1.
const import = require('./export');
保留import
(以及export
)。如果您尝试将任何一个用作变量名,Node将抛出SyntaxError: Unexpected token
。
2.
console.log(import.count);
在您的代码中,您尝试记录已经返回的变量。您会注意到log语句将返回undefined
。而是创建一个函数,您可以调用该函数从另一个文件中的实际变量中获取值。
为了使事情更清楚,这里有一个小小的演示来展示这些概念。
export.js
let count;
const setCount = num => {
count = num;
}
const getCount = () => count;
// Shortcut: If the key: value is the same, we can just omit the value
module.exports = {
setCount,
getCount
}
server.js
const ex = require('./export');
ex.setCount(5);
console.log(ex.getCount()); // 5