簡體   English   中英

如何使用 module.export 將 javascript 中的特定變量導出到節點

[英]How to export a specific variable in javascript to node using module.export

我有一個名為startTime()的 function,其中包含一個變量 h,該變量設置為時間 function 的小時。 我用globalThis對 h 進行了全局化,並希望將其導出到我的節點端,但在導出后 h 變得未定義。 為了調試 h 是否實際設置為一個值,我創建了一個名為exportVariable()的新 function ,其中包含一個alert(h) 當我從客戶端/html 端運行exportVariable()時,它會正確提醒startTime() function 的當前小時,因此這意味着 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> 

我看到的主要問題是函數從未被調用。 hstartTime()中定義,但是在var currentTime = h的賦值之前沒有調用這個 function ,所以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,
    
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM