首页 > 解决方案 > 如何使用 module.export 将 javascript 中的特定变量导出到节点

问题描述

我有一个名为的函数startTime(),其中包含一个设置为时间函数小时的变量 h。我将 h 与全局化globalThis并希望将其导出到我的节点端,但在导出后 h 变得未定义。为了调试 h 是否实际设置为一个值,我创建了一个名为的新函数exportVariable(),其中包含一个alert(h). 当我exportVariable()从客户端/html 端运行时,它会正确提醒函数的当前小时,startTime()因此这意味着 h 已定义。什么可能导致 h 在导出后未定义?我当前的 javascript 和节点端代码附在下面。错误位置在 javascript 端。

JavaScript

function startTime() {
    var today = new Date();
    globalThis.h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
  }
  function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
  }

var currentTime = h;

function exportVariable(){
    alert(h)
}



module.exports = {
    currentTime,
    
};

节点

const isModule = require('./index.js');

const time = isModule.currentTime;

错误

var currentTime = h;
                  ^

ReferenceError: h is not defined
    at Object.<anonymous> 

标签: javascriptnode.js

解决方案


我看到的主要问题是函数从未被调用。h是在里面定义的startTime(),但是这个函数在赋值之前没有被调用var currentTime = h,所以h实际上是undefined存在的。

它应该是:

function startTime() {
    var today = new Date();
    globalThis.h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    h + ":" + m + ":" + s;
    var t = setTimeout(startTime, 500);
  }
  function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
  }
startTime() //ADDED ON SOLUTION
var currentTime = h;

function exportVariable(){
    alert(h)
}



module.exports = {
    currentTime,
    
};

推荐阅读