Is nodejs core module portabe on browser

前端 未结 1 722
太阳男子
太阳男子 2020-12-22 10:40

i want to use all the pre built module written for nodejs as a separate module which i can use in browser. I want to keep platform limited to just compiler js code so that t

相关标签:
1条回答
  • 2020-12-22 11:26

    Is nodejs code module portable to the browser

    It depends. nodejs code that does not use nodejs features that are not present in the browser (such as the fs module or net modules) can be portable between nodejs and browsers.

    But, nodejs code that uses features in node that are not present in the browser will not be portable. When it runs, it will generate a runtime error because the code will be attempting to call nodejs library functions that are not present in the browser.

    There is a tool called Browserify that was built to facilitate running nodejs code in the browser. Keep in mind that, while it helps you package nodejs code to run in the browser, it does not work-around the above rules about what you can and cannot call in your code in order to be portable.


    An alternative for code that does use nodejs modules that are not present in the browser is to keep the code in your server and then expose an Ajax endpoint that you can call from the browser via an Ajax call. The browser collects whatever data it wants to pass to the operation, sends that data with the ajax call. The server receives the ajax call, runs your nodejs code to process the data, then returns the answer back to the ajax call. Your Javascript in the browser receives the result from the ajax call and has its answer. This way the code stays in nodejs, but you can use it from either within nodejs or from within the browser.

    0 讨论(0)
提交回复
热议问题