浏览器上的nodejs核心模块是portabe吗 [英] Is nodejs core module portabe on browser

查看:44
本文介绍了浏览器上的nodejs核心模块是portabe吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将为nodejs编写的所有预构建模块用作一个单独的模块,我可以在浏览器中使用它.我想将平台限制为仅编译器js代码,以便在浏览器或nodejs中执行时都没有区别.所有模块都应在浏览器中运行,与在nodejs(server)中运行的浏览器完全相同.

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 there will be no difference if i execute either in browser or nodejs. All the module should run in browser exactly the same as it works in nodejs(server).

推荐答案

nodejs代码模块是否可移植到浏览器

Is nodejs code module portable to the browser

这取决于.不使用浏览器中不存在的nodejs功能(例如 fs 模块或 net 模块)的nodejs代码可以在nodejs和浏览器之间移植.

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.

但是,使用浏览器中不存在的节点功能的nodejs代码将不可移植.它运行时,将生成运行时错误,因为代码将尝试调用浏览器中不存在的nodejs库函数.

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.

有一个名为 Browserify 的工具,该工具旨在促进在浏览器中运行nodejs代码.请记住,虽然它可以帮助您打包nodejs代码以使其在浏览器中运行,但是它不能解决上述规则,即为了便于移植,您可以在代码中调用和不能调用什么.

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.

不使用浏览器中不存在的nodejs模块的代码的另一种选择是将代码保留在服务器中,然后公开一个Ajax端点,您可以通过Ajax调用从浏览器中调用它.浏览器收集它想要传递给该操作的任何数据,并通过ajax调用发送该数据.服务器接收到ajax调用,运行您的nodejs代码以处理数据,然后将答案返回给ajax调用.您在浏览器中的Javascript会从ajax调用中接收结果并给出答案.这样,代码可以保留在nodejs中,但是您可以在nodejs或浏览器中使用它.

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.

这篇关于浏览器上的nodejs核心模块是portabe吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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