networking工人vs child_process在Node.js CPU密集型function
我正在尝试使用node-unfluff
,从HTMLstring中提取内容。 但是,通常需要〜200ms才能运行。 由于它同步运行,这太慢了。 我想让它asynchronous运行。
据我所知,我的select是networking工作者( https://github.com/audreyt/node-webworker-threads )或child_process
( https://nodejs.org/api/child_process.html )。 还有其他更好的select吗?
如果不是这样,在速度或其他因素方面哪个更好?
编辑:
还有Threadsàgogo( https://github.com/xk/node-threads-a-gogo )和小工作者( https://github.com/avoidwork/tiny-worker )。
WebWorker线程不支持require
,所以这不再是一个选项。
通过使用它的load
函数,可以使用Threadsàgogo来require
文件,但是这看起来像是一个拙劣的解决方法。
目前Github上只有26个小星星,所以我很犹豫在生产代码中使用它。 它支持require
。
我正在考虑使用child_process
编写我自己的WebWorker实现,如果没有更好的select。
您可以使用工人的要求。 在你的工作者脚本中,你需要打电话
self.importScripts('../path/require.js');
根据需要文档,你可以传递一个configuration对象到一个模块:
requirejs.config({ //By default load any module IDs from js/lib baseUrl: 'js/lib', //except, if the module ID starts with "app", //load it from the js/app directory. paths //config is relative to the baseUrl, and //never includes a ".js" extension since //the paths config could be for a directory. paths: { app: '../app' } }); // Start the main app logic. requirejs(['jquery', 'canvas', 'app/sub'], function ($, canvas, sub) { //jQuery, canvas and the app/sub module are all //loaded and can be used here now. });
把它放在一起
Worker.js
self.importScripts('../path/require.js'); requirejs.config({ //By default load any module IDs from path/lib baseUrl: 'path/lib', //except, if the module ID starts with "app", //load it from the js/app directory. paths //config is relative to the baseUrl, and //never includes a ".js" extension since //the paths config could be for a directory. paths: { app: '../app' } }); // Start the main app logic. requirejs(['jquery', 'canvas', 'app/sub'], function ($, canvas, sub) { //jQuery, canvas and the app/sub module are all //loaded and can be used here now. // now you can post a message back to your callee script to let it know require has loaded self.postMessage("initialized"); }); self.onmessage = function(message) { // do cpu intensive work here, this example is not cpu intensive... if(message.data === 'to process') { self.postMessage("completed!"); } }
节点工人呼叫
var worker = new Worker('Worker.js'); worker.onmessage = function(event) { var msg = event.data; if(msg === 'initialized') { worker.postMessage({data: 'to process'}); } }