{"bugs":{"url":"https://github.com/andywer/thread.js/issues"},"dist":{"shasum":"afcc55a2afe6fc61017f70f251e110b3746dda03","tarball":"https://registry.npmjs.org/threads/-/threads-0.11.0-umd.tgz","fileCount":58,"integrity":"sha512-kEJxQd7Ly34oBIs4fwYodE+P59XPXmqDPwxCC+kJbOn7idtoMHkhRU/QLKv4zMklGoYnvViLQlVLJudjnGrSIg==","signatures":[{"sig":"MEQCIEgrztIbx5EiYvi3Z6OYhQkQ9qMlrdbk31aMHYbK5qJlAiAQ6sCLga7I/KLxcah9ufs29mRiYpCP409UC2suZIy6mg==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":191615,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJbKVJgCRA9TVsSAnZWagAAbm8P/0jSofmdu7S/ZS7TLJOu\n9NFuSooUOXDroPqHFKZ//A+QiqVHCHMbMHss1P6QgRk7c/yt7QqowXM79s5k\nphhfMOtNNm+6WoFKq/mnyD43UVfxrJ/uraJ3fQJNDriVmZzopo9ah+Dqp/gR\nOFyVW/MTTfX71d4gIYOCn5XARmk6B/rBi+vs76D8rVuH7RVsPmiFLvgH3coA\nDtS80iKGwFk6MnbpfrG0soabPYLEq80QZ3jOxKbshNAUkP7iMyDS1QvX26fQ\nAhw6gNHOLkSWESp0k+f1J9wfVDtI1r3QbY/9329cUGtb2eKHGDV/l2COKw/3\nch/ET/qjyyA6ZlsUif39WmU2skDx/SGi+urwHwoj95Mck23eQboVb+GJQuzB\nGQuHsg5/nMWd7dxnob3Kn8f/CeU+f2+z1cpaGQpDqqK7FbeYIrnX+NmYYuRa\n6FZTqDo93VPFCZbedmE7+oLSrmjzK8BTSzdZe8Tnrxktli5ZHN/TMSAc4QRN\n2AX7XFttHFbMHmRGynUxUSXlQ5RRr6dHzhwHdCmzY7VI26fV7zbU5oO6QUHV\n7RXJhqHrplFE2NeBOu/arDTNLf93pg/9euLbndpDKadQnuniLZskncg3Erg4\nteAL7Oi3jJ6Vxh1UvcspyLHyeM47p6/KXnGPW5+NHK35dJ6GCZR+nUJ1+p6t\nBLr0\r\n=6O+2\r\n-----END PGP SIGNATURE-----\r\n"},"main":"lib/index.js","name":"threads","babel":{"presets":[["es2015",{"loose":true}]]},"author":{"name":"Andy Wermke","email":"andy@dev.next-step-software.com"},"readme":"# threads.js\n[![Build Status](https://travis-ci.org/andywer/threads.js.svg?branch=master)](https://travis-ci.org/andywer/threads.js)\n[![Coverage Status](https://coveralls.io/repos/github/andywer/threads.js/badge.svg?branch=master)](https://coveralls.io/github/andywer/threads.js?branch=master)\n[![Code Climate](https://codeclimate.com/github/andywer/threads.js/badges/gpa.svg)](https://codeclimate.com/github/andywer/threads.js)\n[![NPM Version](https://img.shields.io/npm/v/threads.svg)](https://www.npmjs.com/package/threads)\n\nJavascript thread library. Uses web workers when run in browsers and child processes\nwhen run by node.js. Also supports browsers which do not support web workers.\n\n- For client and server use\n- Use different APIs (web worker, node child_process) transparently\n- Thread pools\n- Built-in error handling\n- Well tested\n- ES6 and backwards-compatible\n\n\n## Basic usage\n\nSpawn threads to do the time-consuming work and let the parent thread focus on\ndaily business!\n\n```javascript\nconst spawn = require('threads').spawn;\n\nconst thread = spawn(function(input, done) {\n  // Everything we do here will be run in parallel in another execution context.\n  // Remember that this function will be executed in the thread's context,\n  // so you cannot reference any value of the surrounding code.\n  done({ string : input.string, integer : parseInt(input.string) });\n});\n\nthread\n  .send({ string : '123' })\n  // The handlers come here: (none of them is mandatory)\n  .on('message', function(response) {\n    console.log('123 * 2 = ', response.integer * 2);\n    thread.kill();\n  })\n  .on('error', function(error) {\n    console.error('Worker errored:', error);\n  })\n  .on('exit', function() {\n    console.log('Worker has been terminated.');\n  });\n```\n\n\n## Installation\n\n### NPM (Node.js, Browserify, Webpack)\n\n```bash\nnpm install --save threads\n```\n\n### Bower\n\n```bash\nbower install --save threads\n```\n\n### Script tag\n\n```html\n<script src=\"https://unpkg.com/threads@VERSION/dist/threads.browser.min.js\"></script>\n```\n\nNote: Replace `VERSION` with the library's version you want to use, like `v0.12.0`. The library will be exposed on the global window scope as `threads`.\n\n\n## How To\n\n### Thread code in separate files\n\nYou don't have to write the thread's code inline. The file is expected to be a\ncommonjs module (so something that uses `module.exports = ...`), for node and\nbrowser.\n\n```javascript\nconst threads = require('threads');\nconst config  = threads.config;\nconst spawn   = threads.spawn;\n\n// Set base paths to thread scripts\nconfig.set({\n  basepath : {\n    node : __dirname + '/../thread-scripts',\n    web  : 'http://myserver.local/thread-scripts'\n  }\n});\n\nconst thread = spawn('worker.js');\n\nthread\n  .send({ do : 'Something awesome!' })\n  .on('message', function(message) {\n    console.log('worker.js replied:', message);\n  });\n```\n\nworker.js:\n```javascript\n// Use CommonJS syntax (module.exports). Works in browser, too!\n// Only limitation: You won't have require() when run in the browser.\nmodule.exports = function(input, done) {\n  done('Awesome thread script may run in browser and node.js!');\n};\n```\n\n### Async functions\n\nYou can also pass async functions, a.k.a. functions returning a Promise, to spawn threads.\n\n```javascript\nconst spawn = require('threads').spawn;\n\nconst thread = spawn(function ([a, b]) {\n  // Remember that this function will be run in another execution context.\n  return new Promise(resolve => {\n    setTimeout(() => resolve(a + b), 1000)\n  })\n});\n\nthread\n  .send([ 9, 12 ])\n  // The handlers come here: (none of them is mandatory)\n  .on('message', function(response) {\n    console.log('9 + 12 = ', response);\n    thread.kill();\n  });\n```\n\n\n### Thread Pool\n\nYou can also create a thread pool that spawns a fixed no. of workers. Pass jobs\nto the thread pool which it will queue and pass to the next idle worker.\nYou can also pass the number threads to be spawned. Defaults to the number of\nCPU cores.\n\n```javascript\nconst Pool = require('threads').Pool;\n\nconst pool = new Pool();\n// Alternatively: new Pool(<number of threads to spawn>)\n\n// Run a script\nconst jobA = pool\n  .run('/path/to/worker')\n  .send({ do : 'something' });\n\n// Run the same script, but with a different parameter\nconst jobB = pool\n  .send({ do : 'something else' });\n\n// Run inline code\nconst jobC = pool.run(\n  function(input, done) {\n    const hash = md5(input);\n    done(hash, input);\n  }, {\n    // dependencies; resolved using node's require() or the web workers importScript()\n    md5 : 'js-md5'\n  }\n).send('Hash this string!');\n\njobC\n  .on('done', function(hash, input) {\n    console.log(`Job C hashed: md5(\"${input}\") = \"${hash}\"`);\n  });\n\npool\n  .on('done', function(job, message) {\n    console.log('Job done:', job);\n  })\n  .on('error', function(job, error) {\n    console.error('Job errored:', job);\n  })\n  .on('finished', function() {\n    console.log('Everything done, shutting down the thread pool.');\n    pool.killAll();\n  });\n```\n\n#### Job Abortion\n\nYou can abort a job by calling `job.abort()`.\n\n```javascript\nconst Pool = require('threads').Pool;\n\nconst pool = new Pool();\n\nconst job = pool\n  .run('/path/to/worker')\n  .send({ do : 'something' });\n  \njob.on('abort', () => { console.log('Job Aborted'); });\n  \n// somewhere else\njob.abort();\n```\n\n### Streaming\n\nYou can also spawn a thread for streaming purposes. The following example shows\na very simple use case where you keep feeding numbers to the background task\nand it will return the minimum and maximum of all values you ever passed.\n\n```javascript\nconst threads = require('threads');\nconst spawn   = threads.spawn;\nconst thread  = spawn(function() {});\n\nthread\n  .run(function minmax(int, done) {\n    if (typeof this.min === 'undefined') {\n      this.min = int;\n      this.max = int;\n    } else {\n      this.min = Math.min(this.min, int);\n      this.max = Math.max(this.max, int);\n    }\n    done({ min : this.min, max : this.max }});\n  })\n  .send(2)\n  .send(3)\n  .send(4)\n  .send(1)\n  .send(5)\n  .on('message', function(minmax) {\n    console.log('min:', minmax.min, ', max:', minmax.max);\n  })\n  .on('done', function() {\n    thread.kill();\n  });\n```\n\n### Retraining\n\nAs it turns out, `thread.run()` is no one-way road.\n\n```javascript\nthread\n  .run(function doThis(input, done) {\n    done('My first job!');\n  })\n  .send()\n  .run(function doThat(input, done) {\n    done('Old job was boring. Trying something new!');\n  })\n  .send();\n```\n\n### Promises\n\nInstead of using callbacks, you can also turn thread messages and pool jobs into\npromises.\n\n```javascript\nspawn(myThreadFile)\n  .send({ important : 'data' })\n  .promise()\n  .then(function success(message) {}, function error(error) {});\n```\n\n```javascript\npool.run(fancyThreadCode);\n\nPromise.all([\n  pool.send({ data : 1 }).promise(),\n  pool.send({ data : 2 }).promise()\n]).then(function allResolved() {\n  console.log('Everything done! It\\'s closing time...');\n});\n```\n\n### Transferable objects\n\nYou can also use transferable objects to improve performance when passing large\nbuffers (in browser). Add script files you want to run using importScripts()\n(if in browser) as second parameter to thread.run().\nSee [Transferable Objects: Lightning Fast!](http://updates.html5rocks.com/2011/12/Transferable-Objects-Lightning-Fast).\n\nBoth features will be ignored by node.js version for now.\n\n```javascript\nconst threads = require('threads');\nconst spawn   = threads.spawn;\nconst thread  = spawn(function() {});\n\nconst largeArrayBuffer = new Uint8Array(1024 * 1024 * 32); // 32MB\nconst jobData = { label : 'huge thing', data: largeArrayBuffer.buffer };\n\nthread\n  .run(function(input, done) {\n    // do something cool with input.label, input.data\n    // call done.transfer() if you want to use transferables in the thread's response\n    // (the node.js code simply ignores the transferables)\n    done.transfer({ some : { response : input.buffer } }, [input.data.buffer]);\n  }, [\n    // this file will be run in the thread using importScripts() if in browser\n    // the node.js code will ignore this second parameter\n    '/dependencies-bundle.js'\n  ])\n  // pass the buffers to transfer into thread context as 2nd parameter to send()\n  .send(jobData, [ largeArrayBuffer.buffer ]);\n```\n\n### Progress update\n\nThe thread can also notify the main thread about its current progress.\n\n```javascript\nconst threads = require('threads');\nconst spawn   = threads.spawn;\nconst thread  = spawn(function() {});\n\nthread\n  .run(function(input, done, progress) {\n    setTimeout(done, 1000);\n    setTimeout(function() { progress(25); }, 250);\n    setTimeout(function() { progress(50); }, 500);\n    setTimeout(function() { progress(75); }, 750);\n  })\n  .send()\n  .on('progress', function(progress) {\n    console.log(`Progress: ${progress}%`);\n  })\n  .on('done', function() {\n    console.log(`Done.`);\n    thread.kill();\n  });\n```\n\nOutput:\n\n```\nProgress: 25%\nProgress: 50%\nProgress: 75%\nDone.\n```\n\n### Web worker fallback\n\nYou can provide a fallback if the user's browser does not support web workers.\nSee [webworker-fallback](https://github.com/andywer/webworker-fallback). This will not have any effect if used by node.js code.\n\n### Debugging threads\n\nWhen the main process uses `--inspect` to debug Node.js, each thread will be started with the `--inspect` flag too, but\nin a different port so they don't interfere with the main process. Each created thread will have an incremental port, so\nyou can create and debug as many as you want.\n\nThis also works with `--inspect-brk`. As expected, each thread will pause on the first line when created.\n\nAll other flags are passed to the thread unchanged. To override this behaviour, you can pass your own `execArgv` array\nwhen creating a thread:\n\n```javascript\n// Always open an inspect port on 1234, no matter what the main process is doing.\nspawn(myThreadFile, { execArgv: ['--inspect=1234'] })\n\n// Pass this flag to the thread. Ignore any other flag provided by the main process.\nspawn(myThreadFile, { execArgv: ['--throw-deprecation'] })\n```\n\n### Use external dependencies\n\nNot yet completely implemented.\n\nTo do:\n- gulp task to bundle dependencies using browserify and expose all of them -> dependency bundle\n- dependency bundle can be imported by importScripts()\n- code can just call `var myDependency = require('my-dependency');`, no matter if browser or node.js\n\n\n## Configuration\n\n```javascript\nconst config = require('threads').config;\n\n// These configuration properties are all optional\nconfig.set({\n  basepath : {\n    node : 'path/to/my/worker/scripts/directory',\n    web  : 'path-or-url/to/my/worker/scripts/directory'\n  },\n  fallback : {\n    slaveScriptUrl : 'path-or-url/to/dist/slave.js'    // used for IE where you cannot pass code to a worker using a data URI\n  }\n});\n```\n\n\n## FAQ: Frequently Asked Questions\n\n#### Node: `require()`-ing relative paths in worker does not work (`Error: Cannot find module`)\nThank you, https://github.com/FlorianBruckner, for reporting the issues and helping to debug them!\n\n**Solution**: Pass down `__dirname` to worker and use it in `require()` (see [Issue 28](https://github.com/andywer/threads.js/issues/28#issuecomment-248505917))\n\n\n## Change log\n\nSee [CHANGELOG.md](./CHANGELOG.md).\n\n\n## License\n\nThis library is published under the MIT license. See [LICENSE](./LICENSE) for details.\n\n\n__Have fun and build something awesome!__\n","browser":{"os":false,"path":false,"child_process":false},"engines":{"node":">= 4.0"},"gitHead":"d8a9dbf651a8c20aad2ab69e8cedb0c4f7a1d635","license":"MIT","scripts":{"test":"gulp test","build":"gulp dist","prepublishOnly":"gulp dist test"},"_npmUser":{"name":"andywer","email":"andy@dev.next-step-software.com"},"homepage":"https://github.com/andywer/thread.js#readme","keywords":["threads","web worker","cluster","child_process","threadpool","spawn","fork","parallel"],"repository":{"url":"git+https://github.com/andywer/thread.js.git","type":"git"},"_npmVersion":"6.1.0","description":"Easy to use, yet powerful multi-threading library for node.js and the browser!","directories":{},"maintainers":[{"name":"andywer","email":"andy@dev.next-step-software.com"}],"_nodeVersion":"8.11.3","dependencies":{"eventemitter3":"^2.0.2","native-promise-only":"^0.8.1"},"_hasShrinkwrap":false,"readmeFilename":"README.md","devDependencies":{"gulp":"^3.9.1","async":"^1.4.2","karma":"^1.3.0","mocha":"^3.1.2","sinon":"^1.16.1","istanbul":"^0.4.0","through2":"^2.0.0","coveralls":"^2.11.4","expect.js":"^0.3.1","phantomjs":"^1.9.18","browserify":"^13.1.1","gulp-babel":"^6.1.2","gulp-mocha":"^3.0.1","gulp-concat":"^2.5.2","gulp-eslint":"^3.0.1","gulp-rename":"^1.2.2","gulp-uglify":"^2.0.0","karma-mocha":"^1.3.0","karma-expect":"^1.1.0","gulp-sourcemaps":"^1.5.2","karma-browserify":"^4.3.0","babel-preset-es2015":"^6.18.0","vinyl-source-stream":"^1.1.0","karma-chrome-launcher":"^2.0.0","karma-firefox-launcher":"^1.0.0","karma-phantomjs-launcher":"^1.0.2","babel-preset-es2015-loose":"^8.0.0","codeclimate-test-reporter":"^0.4.0"},"_npmOperationalInternal":{"tmp":"tmp/threads_0.11.0-umd_1529434719541_0.6085295801927946","host":"s3://npm-registry-packages"},"_id":"threads@0.11.0-umd","version":"0.11.0-umd"}