如何在节点js

时间:2019-02-14 11:32:15

标签: node.js express

我有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 个答案:

答案 0 :(得分:0)

我创建了一个小节点应用程序来测试您代码的变体。两个重要发现:

1。

const import = require('./export');

import被保留(以及export)。如果您尝试使用任一节点作为变量名,则节点将抛出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