https://github.com/webreflection/node-worker
Web Worker like API to drive NodeJS files
https://github.com/webreflection/node-worker
Last synced: over 1 year ago
JSON representation
Web Worker like API to drive NodeJS files
- Host: GitHub
- URL: https://github.com/webreflection/node-worker
- Owner: WebReflection
- License: isc
- Created: 2017-08-01T22:12:56.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2023-07-04T16:38:55.000Z (about 3 years ago)
- Last Synced: 2024-12-31T15:13:51.125Z (over 1 year ago)
- Language: JavaScript
- Size: 25.4 KB
- Stars: 33
- Watchers: 4
- Forks: 6
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# node-worker: DEPRECATED thanks to [coincident]([https://github.com/WebReflection/workway#workway--](https://github.com/WebReflection/coincident#coincidentserver)) 🎉
[](https://opensource.org/licenses/ISC) [](https://github.com/WebReflection/donate)
Web Worker like API to drive NodeJS files
`npm install @webreflection/node-worker`
### Concept
The aim of this project is to provide an alternative to [Electron](https://electron.atom.io/) environment.
This might be particularly useful in those platforms with constrains such Raspberry Pi Zero or 1.
The module is based on the standard [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) API.
You can `postMessage(data)` and receive `onmessage = (data) => {}` on both client and server.
All workers files must be inside a `workers` directory within the application folder.
Every worker is a [sandboxed VM](https://nodejs.org/api/vm.html) and it runs on the backend: nothing is shared directly with the browser.
### Basic Example
**NodeJS**
```js
var index = require('fs').readFileSync(__dirname + '/index.html');
var http = require('http').createServer(handler);
var nodeWorker = require('@webreflection/node-worker');
var app = nodeWorker(http);
app.listen(process.env.PORT);
function handler(req, res) {
res.writeHead(200, 'OK', {
'Content-Type': 'text/html'
});
res.end(index);
}
```
**Express**
```js
var index = require('fs').readFileSync(__dirname + '/index.html');
var express = require('express');
var nodeWorker = require('@webreflection/node-worker');
var app = nodeWorker(express());
app.get('/', handler);
app.listen(process.env.PORT);
function handler(req, res) {
res.writeHead(200, 'OK', {
'Content-Type': 'text/html'
});
res.end(index);
}
```
**Demo index.html**
```html
var nw = new NodeWorker('echo.js');
nw.postMessage({hello: "world"});
nw.onmessage = function (event) {
console.log(event);
};
nw.onerror = function (error) {
console.error(error);
};
```
**workers/echo.js**
```js
// simple echo
// when some data arrives
// same data goes back
onmessage = function (e) {
postMessage(e.data);
};
```
You can clone and run `npm test` after an `npm install`.