是否可以将node.js文件链接到HTML?

时间:2019-03-08 18:47:43

标签: javascript html node.js

对于使用html来说是很新的东西,我想知道是否可以将节点文件链接到HTML。我想要一个按钮,单击该按钮将运行节点文件中定义的功能。我想知道我的节点文件中是否包含节点软件包,如果出现任何错误。任何帮助!

1 个答案:

答案 0 :(得分:0)

我认为您正在尝试执行以下操作:您编写了一些要在Node中运行的代码。假设代码包含在文件aModule.js中。问题是,如何从浏览器中调用该文件中定义的函数。第二个问题是,它们会运行吗?

首先,您当然可以像其他任何JavaScript一样使用script标签将aModule.js导入浏览器。然后,您也许可以访问模块中的功能,并且它们可能在浏览器中正确运行。这完全取决于他们在编写时是否考虑了浏览器支持。我在下面举例说明可以做到这一点的一种方法(不是唯一的方法)。

您将必须查看正在使用的特定代码,以查看如何在浏览器中访问它。另外,如果编写代码时仅依赖于节点内可用的功能,则您将不得不做更多的工作,可能需要修改代码才能使其运行。

在某些时候,“导入”机制将被标准化,因此这一切将变得更加容易,但是到目前为止,这有点混乱。

这是一个可以在节点或浏览器中工作的模块的示例。

// aModule.js - illustrates modularity that will work in browser or node  

"use strict";

var aModule = {}; // In browser, this will put aModule into global context

// "Closure" stops other stuff from being put into global context in browser
(function () {
    function getMessage() {
        return "Hello";
    }

    // other internal code not intended to be exposed can go here...
    // ...

    // and here is how we expose our getMessage function
    aModule.getMessage = getMessage;
})();

// If we are in node...
if (typeof module !== 'undefined' && module.exports) {
    // Export our module for use in node
    module.exports = aModule;
}

这是您访问node.js中功能的方式:

var aModule = require("./aModule.js");
console.log (aModule.getMessage());

以下是您在浏览器中的访问方式:

<!DOCTYPE html>
<html>
    <head>
        <title>Try out modularizing javascript in browser</title>
    </head>
    <body>
        <h2>Try modularization...</h2>
        <script src="aModule.js"></script> 
        <script>
            alert(aModule.getMessage());
        </script>
    </body>
</html>

另一个提示-看一下Browserify之类的工具。这些旨在将节点代码转换为可以在浏览器中运行的形式。您的里程可能会有所不同。

相关问题