如何将javascript变量导出到nodejs

how to export a javascript variable to node js

本文关键字:nodejs 变量 javascript      更新时间:2024-03-11

我有一个html文件,它调用一个javascript函数来从用户那里获得6位数的输入。

<html>
    <head>
        <script src="ho.js"></script>
        <h1>Sample</h1>
    </head>
    <body>
            <input type="tel" id="realOTP" placeholder="Enter Your OTP"  maxlength="6">
            <input type="submit" value="Use OTP" onclick="compute()">
    </body>
</html>

这是定义函数的ho.js javascript文件。

var a=10, arr=[];
var exports = module.exports = {};
function compute() {
    rOTP = document.getElementById('realOTP').value;
    if (rOTP.length == 0) {
        alert('Enter a value');
        return;
    };
    arr = String(rOTP).split("");
    console.log("Entered OTP -> " + arr);
    return arr;
}
    exports.array = compute.arr;//what should come here?
exports.r = a;
    console.log("a:" +a);
exports.fun =function(){
    console.log("in function");
    var mes = require("./ho").r;
    console.log("mes:"+mes);
    var mes2 = require("./ho").array;
    console.log("mes2:"+mes2);
}

是否可以将javascript函数的返回值(本例中为"arr")导出到节点jsexports函数,类似于全局变量a=10。这是我通过浏览器获得"arr"值后调用的主节点文件。

hoh.js

var call = require("./ho");
console.log("hoh:" +call.r);
call.fun();

这是我运行hoh.js:时得到的输出

C:'Users'Balajee'Desktop'project'Ultro>node hoh.js
a:10
hoh:10
in function
mes:10
mes2:undefined
exports.arr = arr;

将导出数组。但是数组在计算中被重新分配。如果compute()更改数组,则可以访问导出数组中的内容。

arr = String(rOTP).split("");更改为arr.push.apply(arr, String(rOTP).split(""));,以便computer()变异而不是重新分配。

或者,导出getter

或者,您可以导出一个getter,它将允许您根据需要继续重新分配arr。这个代码示例也可以使用ES6胖箭头语法编写;我只是假设您仅限于ES5。

exports.getArr = function() { return arr; }