0

First of all I have checked all the questions on Stack Overflow regarding this.

I am trying to export variable str whose value is getting updated inside the function to another module but it is showing undefined after exporting it in another file.

But if I update the value of variable outside function then export is working fine.

I have a function with code in file Excel.js

var str='abc';
wb.xlsx.readFile(filePath).then(function()

{

    var sh = wb.getWorksheet("Sheet1");

    console.log("YOUR LECTURE IS",sh.getRow(goingSlot+1).getCell(DAY+1).value);
 //console works fine
   str="YOUR LECTURE IS"+sh.getRow(goingSlot+1).getCell(DAY+1).value;
        //the assignment here leads to undefined after exporting
    }

str="something";
//this successfully exports the value as something 

And then I export this to my main file with syntax

exports.str=str; 

Incase you need to see code for main file

The code for the main file is

const express=require('express');
const app=express();
const myle=require('./readingExcel.js');
const res=myle.name;
console.log(res); 
//CONSOLE SHOWS UNDEFINED
t.niese
  • 39,256
  • 9
  • 74
  • 101
  • 1
    you should be using `module.exports...` https://stackoverflow.com/questions/7137397/module-exports-vs-exports-in-node-js – rlemon Aug 15 '18 at 14:24
  • This points towards something in sh.getRow().GetCell().value being undefined. Please check what your Getcell().value is returning – Prodigle Aug 15 '18 at 14:26
  • Possible duplicate of [How does variable assignment work in JavaScript?](https://stackoverflow.com/questions/509579/how-does-variable-assignment-work-in-javascript) – t.niese Aug 15 '18 at 14:29

2 Answers2

0

exports.str and str are not the same variable even though you write exports.str = str

var a = 2;
var b = a;

a = 4;

console.log(b) // b is still 2 and not 4

So use exports.str directly instead of str.

exports.str = 'abc'
// ...
exports.str="YOUR LECTURE IS"+sh.getRow(goingSlot+1).getCell(DAY+1).value;
// ...
exports.str = 'something'
t.niese
  • 39,256
  • 9
  • 74
  • 101
0

I just want to add something to @t.niese's response (which in my opinion is pretty solid).

Check your code for any mode.exports happening after your exports.str assignment. exports and module.exports are usually pointing to the same place, but I always use module.exports. Using exports has the risk of being overwritten somewhere else (module.exports too, but that is the real reference used by node).

https://medium.freecodecamp.org/node-js-module-exports-vs-exports-ec7e254d63ac