Skip to content

Commit

Permalink
path: add dot for path format if absent
Browse files Browse the repository at this point in the history
  • Loading branch information
theanarkh committed Aug 23, 2022
1 parent 937520a commit a2d9825
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
8 changes: 8 additions & 0 deletions doc/api/path.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,14 @@ path.format({
ext: '.txt'
});
// Returns: '/file.txt'

// the dot will be added if it is not specified in ext.
path.format({
root: '/',
name: 'file',
ext: 'txt'
});
// Returns: '/file.txt'
```

On Windows:
Expand Down
6 changes: 5 additions & 1 deletion lib/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@ function normalizeString(path, allowAboveRoot, separator, isPathSeparator) {
return res;
}

function formatExt(ext) {
return ext ? `${ext[0] === '.' ? '' : '.'}${ext}` : '';
}

/**
* @param {string} sep
* @param {{
Expand All @@ -142,7 +146,7 @@ function _format(sep, pathObject) {
validateObject(pathObject, 'pathObject');
const dir = pathObject.dir || pathObject.root;
const base = pathObject.base ||
`${pathObject.name || ''}${pathObject.ext || ''}`;
`${pathObject.name || ''}${formatExt(pathObject.ext)}`;
if (!dir) {
return base;
}
Expand Down
4 changes: 4 additions & 0 deletions test/parallel/test-path-parse-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,7 @@ function checkFormat(path, testCases) {
});
});
}

// See https://github.com/nodejs/node/issues/44343
assert.strictEqual(path.format({ name: 'x', ext: 'png' }), 'x.png');
assert.strictEqual(path.format({ name: 'x', ext: '.png' }), 'x.png');

0 comments on commit a2d9825

Please sign in to comment.