Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

path: add dot for path.format if absent in ext #44349

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions doc/api/path.md
Expand Up @@ -206,6 +206,10 @@ A [`TypeError`][] is thrown if `path` is not a string.

<!-- YAML
added: v0.11.15
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/44349
description: The dot will be added if it is not specified in `ext`.
-->

* `pathObject` {Object} Any JavaScript object having the following properties:
Expand Down Expand Up @@ -255,6 +259,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
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
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');