From 135dd4c7b92c71f2ee0749fdb3ed33fc62bfda39 Mon Sep 17 00:00:00 2001 From: Karan Raina Date: Mon, 27 Dec 2021 00:12:45 +0530 Subject: [PATCH] add basic API --- LICENSE.md | 11 +++++ README.md | 116 ++++++++++++++++++++++++++++++++++++++++++++++++++- index.js | 24 +++++++++++ package.json | 1 + src/index.js | 46 ++++++++++++++++++-- worker.js | 11 +++++ 6 files changed, 205 insertions(+), 4 deletions(-) create mode 100644 LICENSE.md create mode 100644 index.js create mode 100644 worker.js diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..1d938e9 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,11 @@ +# Released under MIT License + +Copyright (c) 2013 Mark Otto. + +Copyright (c) 2017 Andrew Fong. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index aff797f..471ab00 100644 --- a/README.md +++ b/README.md @@ -1 +1,115 @@ -

Welcome to nodejs-threads 👋

\ No newline at end of file +

Welcome to nodejs-threads 👋

+

+ + Version + + + Version + + + Documentation + + + Maintenance + + + License: MIT + + + Twitter: karankraina + +

+ +> A very simple function based implementation of node.js worker threads + +### 🏠 [Homepage](https://github.com/karankraina/nodejs-threads#readme) + +### ✨ [Demo](https://replit.com/@karankraina/nodejs-threads) + +## Install + +```sh +npm install nodejs-threads +``` + +## Usage + +### Define a worker job that needs to be run in a separate thread. + +Use the ```defineWorker``` function to define a worker job in ```worker.js``` file (can be named anything). This function takes an async function as argument. It passes the payload received from the main thread to the argument function of the worker thread. + +```javascript +/** + * This code will execute in a separate thread +*/ +const { defineWorker } = require('nodejs-utils'); +// OR +import { defineWorker } from 'nodejs-utils'; + + +defineWorker(async (payload) => { + console.log(payload); // Payload from the Primary thread is availbale here + + /* + * Do any CPU intensive task here. + * The event loop in primary thread won't be blocked . + */ + let result = 0; + for (let i = 0; i < payload.range; i++) { + result += i; + } + console.log('COMPLETED'); + return result; +}); +``` + +### Create a worker thread + +You can create a new worker thread by simply calling ```createWorker``` function. The first argument is the path of the ```worker.js``` file and you can pass any payload as the second argument. The payload passed will be provided as an argument in the worker callback function. + +```javascript +const { createWorker } = require('nodejs-utils'); + +// Inside any async function +const worker = await createWorker('./worker.js', { + range: 50000000, + }); + +// Attach a listener if you expect any return value from the worker funcion +worker.on('message', (result) => { + console.log(result); +}); + +``` + + +## Run tests + +```sh +npm run test +``` + +## Author + +👤 **Karan Raina ** + +* Website: https://karanraina.tech/ +* Twitter: [@karankraina](https://twitter.com/karankraina) +* Github: [@karankraina](https://github.com/karankraina) +* LinkedIn: [@karankraina](https://linkedin.com/in/karankraina) + +## 🤝 Contributing + +Contributions, issues and feature requests are welcome!
Feel free to check [issues page](https://github.com/karankraina/nodejs-threads/issues). You can also take a look at the [contributing guide](https://github.com/karankraina/nodejs-threads/blob/master/CONTRIBUTING.md). + +## Show your support + +Give a ⭐️ if this project helped you! + +## 📝 License + +Copyright © 2021 [Karan Raina ](https://github.com/karankraina).
+This project is [MIT](https://github.com/karankraina/nodejs-threads/blob/master/LICENSE) licensed. + +*** +_This README was generated with ❤️ by [readme-md-generator](https://github.com/kefranabg/readme-md-generator)_ \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..5ef6091 --- /dev/null +++ b/index.js @@ -0,0 +1,24 @@ +const { createWorker } = require('./lib/index'); + + +async function main() { + // create a worker + const worker = await createWorker('./worker.js', { + range: 5000000000, + }); + + worker.on('message', (result) => { + console.log(result); + }); + + setInterval(() => { + console.log(' HELLO !!! I AM FROM THE PRIMARY THREAD') + }, 1000); + +} + +main().then(() => { + console.log('Done!'); +}).catch((err) => { + console.error(err); +}); \ No newline at end of file diff --git a/package.json b/package.json index f3351c3..4d284d2 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "main": "lib/index.js", "scripts": { "build": "babel src --out-dir lib", + "build:dev": "babel src --out-dir lib --watch", "prepublish": "npm run build", "test": "jest" }, diff --git a/src/index.js b/src/index.js index c0e6432..e0b7ce9 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,45 @@ -function test() { - console.log('Hello World'); +const { Worker, workerData, isMainThread, parentPort } = require('worker_threads'); + + +/** + * Function to create a new worker thread. + * + * @param {string} workerPath Path to the worker file + * @param {Object} payload Payload to be sent to the worker + * @returns Promise which resolves to the reference of the worker + */ +export function createWorker(workerPath, payload = {}) { + if (!isMainThread) { + return null; + } + return new Promise((resolve) => { + const worker = new Worker(workerPath, { + workerData: payload + }); + + worker.on('exit', (code) => { + console.log(`Worker ${worker.threadId} exited with code ${code}`); + }); + + // resolve when the worker starts code execution + worker.on('online', () => { + resolve(worker); + }); + + }); }; -export default test; \ No newline at end of file +/** + * Function to define a worker function. + * + * @param {Function} job Function to be executed by the worker + * @returns Returns a promise which resolves to the result of the job + */ +export async function defineWorker(job) { + // return if it is primary thread + if (isMainThread) { + return null; + } + const result = await job(workerData); + parentPort.postMessage(result); +}; \ No newline at end of file diff --git a/worker.js b/worker.js new file mode 100644 index 0000000..4793a77 --- /dev/null +++ b/worker.js @@ -0,0 +1,11 @@ +const { defineWorker } = require('./lib/index'); + +defineWorker((payload) => { + console.log(payload); + let result = 0; + for (let i = 0; i < payload.range; i++) { + result += i; + } + console.log('COMPLETED-------------------------------------------------'); + return result; +}); \ No newline at end of file