including js files with html and node.js

前端 未结 2 1839
清歌不尽
清歌不尽 2021-02-14 07:30

I am performing messaging via websockets between a HTML5 client and server running on node.js. Naturally I chose JSON as the message format and as such created common javascript

2条回答
  •  醉梦人生
    2021-02-14 08:22

    Have you researched how Node modules work? If you're developing using this pattern, it's fairly simple to use require('./common/js/comms') on the server while still including it on your client as well.

    This article should point you in the right direction: https://caolan.org/posts/writing_for_node_and_the_browser.html


    The following is the code that Tyler linked to in his comments below.

    The example (example.js):

    if(typeof exports == "undefined"){
        exports = this;
    }
    
    Example = function() {
        this.init();
    };
    
    Example.prototype = {
        init: function() {
             console.log('hello world');
        }
    };
    
    exports.Example = new Example();
    

    The node.js usage of example.js (app.js):

    example = require('./example');
    

    The html usage of example.js (index.html):

    
        
            
        
        
            
        
    

    The change by the OP was to assign exports.Example to Example instead of to an new instance. Thus the node.js logic can use the following:

    var Example = require('./example.js').Example;
    var foo = new Example();
    

    Thus the original question is solved.

提交回复
热议问题