如何将javascript变量导出到nodejs
how to export a javascript variable to node js
我有一个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; }
相关文章:
- 为变量分配多个nodejs导出返回值时出现问题
- 使用JS/NodeJS测试并读取文件中的变量
- 使用nodejs从url中获取变量
- 将 NodeJS 模块范围变量作为对象访问
- 从导出的模块返回变量,并在另一个文件(NodeJS)中使用它
- nodejs-settimeout是否在不同的循环中共享变量
- 使用NodeJS与客户端共享变量
- 如何将javascript变量导出到nodejs
- 如何在nodejs中的MySQL查询中使用多个变量
- NodeJS和ES6类实例中的变量可见性
- 将变量传递给nodejs函数
- nodejs中的Javascript全局变量和属性-全局属性有时会被删除
- 如何将变量传递到NodeJS模块中
- 在全局范围内访问嵌套变量的 Nodejs
- JScript 中的 NodeJS + JQuery php 变量
- nodejs 中的全局变量
- NodeJS,使用 Eclipse Debugger 进行变量检查
- Nodejs 变量声明
- Nodejs变量不能传递给事件监听器
- Nodejs变量只存在于函数和子函数中