如何在nodejs和web上同时使用javascript? [英] How to use javascript on nodejs and web at the same time?

查看:59
本文介绍了如何在nodejs和web上同时使用javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在nodejs和web javascript中使用配置文件。

i want to use a config file in nodejs and in a web javascript.

config.js:

config.js:

var conf = {};

conf.name = 'testname';
conf.pass = 'abc123';
conf.ip = '0.0.0.0';
conf.port = 100;
conf.delay = 5;

exports.config = conf;

在nodejs中使用它:

use it in nodejs with:

var conf = require('config.js');
console.log(conf.config.name);

想在html中使用同一个文件,但是如何?我这样想,但我不知道如何在网络上使用它。当我尝试在网络中使用它时我得到参考错误:导出未定义。

want to use this same file inside html but how? I was thinking by this way but i don't know how to use it in web. When i try to use it in web i get Reference error: exports is not defined.

config.html:

config.html:

<!doctype html>
<html lang="en">
<head>
    <title>Document</title>
    <script src="./config.js"></script>
    <script>
        var cnf = conf;
        function getCnf(){
            alert(cnf.config.name);
        }
    </script>
</head>
<body>
    <button onclick="getCnf();">test</button>
</body>
</html>

任何人都知道如何更改config.js以在系统nodejs和web中使用它?

Anyone know how i must change config.js to use it in both systems nodejs and web?

PS:Webside正在nodejs http npm模块上运行。

PS: Webside is running on nodejs http npm module.

推荐答案

你可以设置一个条件,像这样

You can put a condition around that, like this

if (typeof module !== 'undefined' && module.exports) {
    module.exports.config = conf;
}

这确保你有模块 exports 上设置任何值之前,c $ c>和 exports 可用。

This makes sure that you have module and exports are available before setting any value on exports.

注意: exports 只是引用 module.exports 的另一个变量。因此,除非您为其中任何一个分配其他内容,否则它们都是同一个。如果您为其中任何一个分配内容, module.exports 中的任何内容都将在Node.js中导出。您可以在 exports 的更多信息。 rel =nofollow>博客文章

Note: exports is just another variable referring module.exports. So, they both are one and the same unless you assign something else to either of them. In case, you assign something to either of them, whatever is there in module.exports will be exported in Node.js. You can read more about exports in this blog post

这篇关于如何在nodejs和web上同时使用javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆