我有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
)。SyntaxError: Unexpected token
如果您尝试使用任一变量名,Node都会抛出一个。
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句