Skip to content

Commit

Permalink
add basic API
Browse files Browse the repository at this point in the history
  • Loading branch information
karankraina committed Dec 26, 2021
1 parent e66ab71 commit 135dd4c
Show file tree
Hide file tree
Showing 6 changed files with 205 additions and 4 deletions.
11 changes: 11 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -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.
116 changes: 115 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,115 @@
<h1 align="center">Welcome to nodejs-threads 👋</h1>
<h1 align="center">Welcome to nodejs-threads 👋</h1>
<p>
<a href="https://circleci.com/gh/karankraina/nodejs-threads/tree/main.svg?style=svg" target="_blank">
<img alt="Version" src="https://circleci.com/gh/karankraina/nodejs-threads/tree/main.svg?style=svg">
</a>
<a href="https://www.npmjs.com/package/nodejs-threads" target="_blank">
<img alt="Version" src="https://img.shields.io/npm/v/nodejs-threads.svg">
</a>
<a href="https://github.com/karankraina/nodejs-threads#readme" target="_blank">
<img alt="Documentation" src="https://img.shields.io/badge/documentation-yes-brightgreen.svg" />
</a>
<a href="https://github.com/karankraina/nodejs-threads/graphs/commit-activity" target="_blank">
<img alt="Maintenance" src="https://img.shields.io/badge/Maintained%3F-yes-green.svg" />
</a>
<a href="https://github.com/karankraina/nodejs-threads/blob/master/LICENSE" target="_blank">
<img alt="License: MIT" src="https://img.shields.io/github/license/karankraina/nodejs-threads" />
</a>
<a href="https://twitter.com/karankraina" target="_blank">
<img alt="Twitter: karankraina" src="https://img.shields.io/twitter/follow/karankraina.svg?style=social" />
</a>
</p>

> 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 <karanraina1996@gmail.com>**

* 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!<br />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 <karanraina1996@gmail.com>](https://github.com/karankraina).<br />
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)_
24 changes: 24 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -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);
});
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
46 changes: 43 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -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;
/**
* 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);
};
11 changes: 11 additions & 0 deletions worker.js
Original file line number Diff line number Diff line change
@@ -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;
});

0 comments on commit 135dd4c

Please # to comment.