Skip to content

Commit

Permalink
validate argument length
Browse files Browse the repository at this point in the history
  • Loading branch information
shinnn committed Jul 23, 2017
1 parent 7775824 commit 3c565c4
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
12 changes: 11 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,17 @@ const {readFile, unlink} = require('graceful-fs');
const readFileP = promisify(readFile);
const unlinkP = promisify(unlink);

module.exports = async function readRemoveFile(filePath, options) {
module.exports = async function readRemoveFile(...args) {
const argLen = args.length;

if (argLen !== 1 && argLen !== 2) {
return Promise.reject(new RangeError(`Expected 1 or 2 arguments (path: <string>[, options: Object]), but got ${
argLen === 0 ? 'no' : argLen
} arguments.`));
}

const [filePath, options] = args;

const data = await readFileP(filePath, options);
await unlinkP(filePath);

Expand Down
24 changes: 20 additions & 4 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const writeFileAtomically = require('write-file-atomically');
const pathExists = require('path-exists');

test('readRemoveFile()', t => {
t.plan(5);
t.plan(7);

writeFileAtomically('tmp_file0', 'foo')
.then(() => readRemoveFile('tmp_file0'))
Expand All @@ -20,15 +20,31 @@ test('readRemoveFile()', t => {
writeFileAtomically('tmp_file1', 'bar')
.then(() => readRemoveFile('tmp_file1', 'utf8'))
.then(data => {
t.strictEqual(data, 'bar', 'should support the second parameter of fs.readFile.');
t.equal(data, 'bar', 'should support the second parameter of fs.readFile.');
})
.catch(t.fail);

readRemoveFile('this/file/does/not/exist').then(t.fail, err => {
t.strictEqual(err.code, 'ENOENT', 'should fail when it cannot read the file.');
t.equal(err.code, 'ENOENT', 'should fail when it cannot read the file.');
}).catch(t.fail);

readRemoveFile().catch(err => {
t.equal(
err.toString(),
'RangeError: Expected 1 or 2 arguments (path: <string>[, options: Object]), but got no arguments.',
'should fail when it takes no arguments.'
);
});

readRemoveFile('a', {b: 'c'}, 'd').catch(err => {
t.equal(
err.toString(),
'RangeError: Expected 1 or 2 arguments (path: <string>[, options: Object]), but got 3 arguments.',
'should fail when it takes too many arguments.'
);
});

readRemoveFile({invalid: 'argument'}).then(t.fail, err => {
t.strictEqual(err.message, 'path must be a string or Buffer', 'should fail when it takes an invalid argument.');
t.equal(err.message, 'path must be a string or Buffer', 'should fail when it takes an invalid argument.');
}).catch(t.fail);
});

0 comments on commit 3c565c4

Please sign in to comment.