Files
node/test/parallel/test-fs-openAsBlobSync.js
Christian Aurich Zanettini Martins cc610f1cfb fs: validate falsy openAsBlob type option
openAsBlob() and openAsBlobSync() read the MIME type as
options.type || '' before validating it, causing falsy non-string
values to be replaced with the default before reaching validateString().
As a result, { type: 0 }, { type: false }, { type: null }, and
{ type: NaN } are accepted as an empty type, while { type: 1 }
throws ERR_INVALID_ARG_TYPE.

Default the option only when it is undefined so all other values are
validated against the documented string type.

Signed-off-by: Christian Aurich Zanettini Martins <christian.aurichzm@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/66125
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
2026-09-25 19:44:48 +00:00

64 lines
1.7 KiB
JavaScript

'use strict';
const common = require('../common');
const assert = require('assert');
const { Blob, Buffer } = require('buffer');
const fs = require('fs');
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();
const filename = 'open-as-blob-sync.txt';
const testfile = tmpdir.resolve(filename);
const mutationFile = tmpdir.resolve('open-as-blob-sync-mutation.txt');
const missing = tmpdir.resolve('does-not-exist.txt');
const data = 'hello openAsBlobSync';
fs.writeFileSync(testfile, data);
fs.writeFileSync(mutationFile, data);
assert.throws(() => fs.openAsBlobSync(1), {
code: 'ERR_INVALID_ARG_TYPE',
});
assert.throws(() => fs.openAsBlobSync(testfile, null), {
code: 'ERR_INVALID_ARG_TYPE',
});
for (const type of [1, 0, false, null, NaN, {}]) {
assert.throws(() => fs.openAsBlobSync(testfile, { type }), {
code: 'ERR_INVALID_ARG_TYPE',
});
assert.throws(() => fs.openAsBlob(testfile, { type }), {
code: 'ERR_INVALID_ARG_TYPE',
});
}
assert.throws(() => fs.openAsBlobSync(missing), {
code: 'ENOENT',
syscall: 'stat',
path: missing,
});
(async () => {
for (const path of [
testfile,
Buffer.from(testfile),
tmpdir.fileURL(filename),
]) {
const blob = fs.openAsBlobSync(path, { type: 'text/plain' });
assert.ok(blob instanceof Blob);
assert.strictEqual(blob.size, Buffer.byteLength(data));
assert.strictEqual(blob.type, 'text/plain');
assert.strictEqual(await blob.text(), data);
}
const promise = fs.openAsBlob(testfile);
assert.ok(promise instanceof Promise);
await promise;
const blob = fs.openAsBlobSync(mutationFile);
fs.writeFileSync(mutationFile, `${data}!`);
await assert.rejects(blob.text(), {
name: 'NotReadableError',
});
})().then(common.mustCall());