Skip to content

Commit

Permalink
import-meta-url relative handling
Browse files Browse the repository at this point in the history
  • Loading branch information
guybedford committed Apr 14, 2020
1 parent 9e670b3 commit 32ba251
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 11 deletions.
7 changes: 5 additions & 2 deletions README.md
Expand Up @@ -33,7 +33,7 @@ _Here's how this is different from worker_threads:_
```js
import Worker from 'web-worker';

const worker = new Worker('./worker.js');
const worker = new Worker(new URL('./worker.js', import.meta.url));

worker.addEventListener('message', e => {
console.log(e.data) // "hiya!"
Expand All @@ -55,6 +55,9 @@ addEventListener('message', e => {
</td></tr></tbody>
</table>
The pattern `new URL('./worker.js', import.meta.url)` is used above to load the worker relative to the current module instead of the application base URL.
Support for this pattern in build tools and test frameworks is still quite limited, but we are working on growing this support (tracking issue https://github.com/developit/web-worker/issues/4).
### Module Workers
Expand All @@ -68,7 +71,7 @@ In the browser, they can be used natively in Chrome 80+, or in all browsers via
```js
import Worker from 'web-worker';

const worker = new Worker('./worker.mjs', {
const worker = new Worker(new URL('./worker.mjs', import.meta.url), {
type: 'module'
});
worker.addEventListener('message', e => {
Expand Down
17 changes: 9 additions & 8 deletions node.js
Expand Up @@ -72,6 +72,8 @@ function Event(type, target) {
// thread boundary, but behaves differently in each context.
export default threads.isMainThread ? mainThread() : workerThread();

const baseUrl = process.cwd();

function mainThread() {

/**
Expand All @@ -90,16 +92,15 @@ function mainThread() {
constructor(url, options) {
super();
const { name, type } = options || {};
// hack: grab the caller's filename from a stack trace
let relativeTo = process.cwd();
try {
relativeTo = Error().stack.split('\n')[2].match(/ \((.+):[^:]+:[^:]+\)$/)[1];
if (typeof url !== 'string') url = url.toString();
let mod;
if (/^data:/.test(url)) {
mod = url;
}
catch (e) {}
let mod = url;
if (!/^data:/.test(url)) {
mod = URL.fileURLToPath(new URL.URL(url, 'file://' + relativeTo));
else {
mod = URL.fileURLToPath(new URL.URL(url, URL.pathToFileURL(baseUrl + '/')));
}
console.log(mod);
const worker = new threads.Worker(
__filename,
{ workerData: { mod, name, type } }
Expand Down
2 changes: 1 addition & 1 deletion test/index.test.js
Expand Up @@ -35,7 +35,7 @@ test.after.always(t => {
});

test.serial('instantiation', async t => {
worker = createModuleWorker('./fixtures/worker.mjs');
worker = createModuleWorker('./test/fixtures/worker.mjs');
await sleep(500);
t.is(worker.events.length, 1, 'should have received a message event');
t.is(worker.events[0].data, 42);
Expand Down

0 comments on commit 32ba251

Please sign in to comment.