diff --git a/doc/api/path.md b/doc/api/path.md index 5b66e54f9393d2..81d8189b2ee8ff 100644 --- a/doc/api/path.md +++ b/doc/api/path.md @@ -206,6 +206,10 @@ A [`TypeError`][] is thrown if `path` is not a string. * `pathObject` {Object} Any JavaScript object having the following properties: @@ -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: diff --git a/lib/path.js b/lib/path.js index e662e50d6c6b4b..920bc698601e5f 100644 --- a/lib/path.js +++ b/lib/path.js @@ -127,6 +127,10 @@ function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { return res; } +function formatExt(ext) { + return ext ? `${ext[0] === '.' ? '' : '.'}${ext}` : ''; +} + /** * @param {string} sep * @param {{ @@ -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; } diff --git a/test/parallel/test-path-parse-format.js b/test/parallel/test-path-parse-format.js index e60a0cedae4259..52acd836cce87b 100644 --- a/test/parallel/test-path-parse-format.js +++ b/test/parallel/test-path-parse-format.js @@ -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');