4

I have 2 files: export.js and server.js

I'm trying to access a variable in export.js in server.js, but I get undefined.

Note that I'm using knexjs and I gave it the name '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);

When I try to console log inside the livePending function in export.js, I get the desired count which is 1.

The reason I'm doing this is to lessen the lines of code in my server.js. If I do the exact same function in my server.js, I get the correct result.

3
  • 1
    The exported variable in export.js seems to be named pCount, not count. Try console.log(import.pCount); instead. Commented Feb 14, 2019 at 11:34
  • 1
    Beside the fact that the varaible name is pCount as @remix23 said, 'import' is a reserved word in javascript so i think you should change the const name 'import' to something else then import Commented Feb 14, 2019 at 11:39
  • sorry. fixed the code. that was my typo error Commented Feb 14, 2019 at 12:01

1 Answer 1

3

I created a small node app to test a variation of your code. Two important findings:

1.

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

import is reserved (as well as export). Node will throw a SyntaxError: Unexpected token if you attempt to use either one as a variable name.

2.

console.log(import.count);

In your code, you're attempting to log a variable that's already been returned. You'll notice the log statement will return undefined. Instead, create a function that you can call to get the value from the actual variable in the other file.

To make things clearer, here's a little demo to show these concepts in action.

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.