diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 1fb90b37f88642..59838f2e6adbf8 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -856,4 +856,7 @@ E('ERR_WORKER_NEED_ABSOLUTE_PATH', TypeError); E('ERR_WORKER_UNSERIALIZABLE_ERROR', 'Serializing an uncaught exception failed', Error); +E('ERR_WORKER_UNSUPPORTED_EXTENSION', + 'The worker script extension must be ".js" or ".mjs". Received "%s"', + TypeError); E('ERR_ZLIB_INITIALIZATION_FAILED', 'Initialization failed', Error); diff --git a/lib/internal/worker.js b/lib/internal/worker.js index c982478b9334e8..edd954d8a3a2be 100644 --- a/lib/internal/worker.js +++ b/lib/internal/worker.js @@ -8,7 +8,8 @@ const util = require('util'); const { ERR_INVALID_ARG_TYPE, ERR_WORKER_NEED_ABSOLUTE_PATH, - ERR_WORKER_UNSERIALIZABLE_ERROR + ERR_WORKER_UNSERIALIZABLE_ERROR, + ERR_WORKER_UNSUPPORTED_EXTENSION, } = require('internal/errors').codes; const { internalBinding } = require('internal/bootstrap/loaders'); @@ -136,8 +137,14 @@ class Worker extends EventEmitter { throw new ERR_INVALID_ARG_TYPE('filename', 'string', filename); } - if (!options.eval && !path.isAbsolute(filename)) { - throw new ERR_WORKER_NEED_ABSOLUTE_PATH(filename); + if (!options.eval) { + if (!path.isAbsolute(filename)) { + throw new ERR_WORKER_NEED_ABSOLUTE_PATH(filename); + } + const ext = path.extname(filename); + if (ext !== '.js' && ext !== '.mjs') { + throw new ERR_WORKER_UNSUPPORTED_EXTENSION(ext); + } } // Set up the C++ handle for the worker, as well as some internal wiring. diff --git a/test/parallel/test-worker-unsupported-path.js b/test/parallel/test-worker-unsupported-path.js new file mode 100644 index 00000000000000..3716377ec2fb1f --- /dev/null +++ b/test/parallel/test-worker-unsupported-path.js @@ -0,0 +1,27 @@ +// Flags: --experimental-worker +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const { Worker } = require('worker'); + +{ + const expectedErr = common.expectsError({ + code: 'ERR_WORKER_NEED_ABSOLUTE_PATH', + type: TypeError + }, 4); + assert.throws(() => { new Worker('a.js'); }, expectedErr); + assert.throws(() => { new Worker('b'); }, expectedErr); + assert.throws(() => { new Worker('c/d.js'); }, expectedErr); + assert.throws(() => { new Worker('a.mjs'); }, expectedErr); +} + +{ + const expectedErr = common.expectsError({ + code: 'ERR_WORKER_UNSUPPORTED_EXTENSION', + type: TypeError + }, 3); + assert.throws(() => { new Worker('/b'); }, expectedErr); + assert.throws(() => { new Worker('/c.wasm'); }, expectedErr); + assert.throws(() => { new Worker('/d.txt'); }, expectedErr); +}