首页 > 解决方案 > 无法从节点 js 模块导出变量

问题描述

首先,我检查了有关 Stack Overflow 的所有问题。

我正在尝试将str其值在函数内部更新的变量导出到另一个模块,但它undefined在将其导出到另一个文件中后显示。

但是,如果我更新函数外部变量的值,则导出工作正常。

我在 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 

然后我用语法将它导出到我的主文件

exports.str=str; 

如果您需要查看主文件的代码

主文件的代码是

const express=require('express');
const app=express();
const myle=require('./readingExcel.js');
const res=myle.name;
console.log(res); 
//CONSOLE SHOWS UNDEFINED

标签: javascriptnode.jsexpress

解决方案


exports.str并且str不是同一个变量,即使你写exports.str = str

var a = 2;
var b = a;

a = 4;

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

所以exports.str直接使用而不是str.

exports.str = 'abc'
// ...
exports.str="YOUR LECTURE IS"+sh.getRow(goingSlot+1).getCell(DAY+1).value;
// ...
exports.str = 'something'

推荐阅读