Tam211
Tam211

Reputation: 743

Nodejs - Variable initialized inside a function is undefined outside it

I have a nodejs module which is supposed to convert a csv file to json, however the variable which is supposed to hold the json array is undefined outside the function, even though it's declared outside.

const csvFilePath='data.csv'
const csv=require('csvtojson')
let userDB;

const loadUserDB = async() => {
  userDB = await csv().fromFile(csvFilePath);
  console.log(userDB[0]);
  return userDB; 
};

console.log(userDB[0]);

module.exports = {
  loadUserDB,
  userDB
}

I'm new to nodejs so I couldn't figure it out, any ideas?

Upvotes: 0

Views: 183

Answers (2)

Sándor Bakos
Sándor Bakos

Reputation: 503

const csvFilePath='data.csv'
const csv=require('csvtojson')
let userDB;

const loadUserDB = async() => {
  userDB = await csv().fromFile(csvFilePath);
  console.log(userDB[0]);
  return userDB; 
};

// here this always be undefined - why?
// when the index.js file import this module, this file going to run line by line,
// means first the program just registers the userDB and the loadUserDB variables
// without of course executing the function
// so basically this files run in this form only once
// this console.log never going to run after the loadUserDB
console.log(userDB[0]);

module.exports = {
  loadUserDB,
  userDB
}

My advise to check out how scopes and closures work in JavaScript.

Again, you will have undefined the userDB in the moment of the import, and before executing loadUserDB. This module (file) only runs once in this form.

After calling loadUserDB, userDB suppose to have some other value than undefined.

So yes, this value is not always undefined, just the matter of time when you want to access it.

const path = require('path');
const csvFilePath = path.join(__dirname, './data.csv')
const csv = require('csvtojson')
let userDB;

const loadUserDB = async() => {
  userDB = await csv().fromFile(csvFilePath);
};

module.exports = {
  loadUserDB,
  userDB
}

Upvotes: 0

Kaspar Etter
Kaspar Etter

Reputation: 3528

You should probably wait for the asynchronous function to run before you access the variable (or remove the async). Edit: And you never call loadUserDB, at least not in this code. I suggest that, instead of using a wider scoped variable, you simply await the result of your function.

Upvotes: 1

Related Questions