Skip to content

Commit a2f43ce

Browse files
marcopiracciniaduh95
authored andcommitted
fs: add mkstemp()
Add fs.mkstemp(), fs.mkstempSync() and fsPromises.mkstemp(), which create and open a unique temporary file in one operation. They expose uv_fs_mkstemp(), the file counterpart of the function behind fs.mkdtemp(). The callback and sync versions return the path and a file descriptor, the promise version returns the path and a FileHandle. libuv clears the path of the request when mkstemp() fails, so the template is saved in the request and used for the path of the error. The functions are also supported on mounted virtual file systems. Refs: #33549 Refs: #33890 Refs: #5332 Signed-off-by: marcopiraccini <marco.piraccini@gmail.com> PR-URL: #66484 Reviewed-By: Paolo Insogna <paolo@cowtech.it> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
1 parent 7eb0f7a commit a2f43ce

22 files changed

Lines changed: 1095 additions & 17 deletions

‎doc/api/fs.md‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1711,6 +1711,58 @@ For detailed information, see the documentation of [`fsPromises.mkdtemp()`][].
17111711
The optional `options` argument can be a string specifying an encoding, or an
17121712
object with an `encoding` property specifying the character encoding to use.
17131713
1714+
### `fsPromises.mkstemp(prefix[, options])`
1715+
1716+
<!-- YAML
1717+
added: REPLACEME
1718+
-->
1719+
1720+
> Stability: 1 - Experimental
1721+
1722+
* `prefix` {string|Buffer|URL}
1723+
* `options` {string|Object}
1724+
* `encoding` {string} **Default:** `'utf8'` (or `'buffer'` if `prefix` is a `Buffer`)
1725+
* Returns: {Promise} Fulfills with an {Object}:
1726+
* `path` {string|Buffer} The path of the created file.
1727+
* `handle` {FileHandle} The created file, opened for reading and writing.
1728+
1729+
Creates and opens a unique temporary file. A unique file name is generated by
1730+
appending six random characters to the end of the provided `prefix`. Due to
1731+
platform inconsistencies, avoid trailing `X` characters in `prefix`. Some
1732+
platforms, notably the BSDs, can return more than six random characters, and
1733+
replace trailing `X` characters in `prefix` with random characters.
1734+
1735+
The file is created and opened in a single operation, so another process cannot
1736+
create a file with the same name in between. On POSIX systems, the file is only
1737+
readable and writable by its owner.
1738+
1739+
The optional `options` argument can be a string specifying an encoding, or an
1740+
object with an `encoding` property specifying the character encoding to use for
1741+
the returned `path`.
1742+
1743+
```mjs
1744+
import { mkstemp } from 'node:fs/promises';
1745+
import { join } from 'node:path';
1746+
import { tmpdir } from 'node:os';
1747+
1748+
const { path, handle } = await mkstemp(join(tmpdir(), 'foo-'));
1749+
try {
1750+
await handle.writeFile('some data');
1751+
console.log(path);
1752+
// Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
1753+
} finally {
1754+
await handle.close();
1755+
}
1756+
```
1757+
1758+
The file is not removed automatically. It is the caller's responsibility to
1759+
close the {FileHandle} and to remove the file when it is no longer needed.
1760+
1761+
As with [`fsPromises.mkdtemp()`][], the random characters are appended directly
1762+
to `prefix`. To create a file _within_ a directory, `prefix` must end with a
1763+
trailing platform-specific path separator (`require('node:path').sep`) or
1764+
include the beginning of the file name.
1765+
17141766
### `fsPromises.open(path, flags[, mode])`
17151767
17161768
<!-- YAML
@@ -4064,6 +4116,66 @@ mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
40644116
});
40654117
```
40664118
4119+
### `fs.mkstemp(prefix[, options], callback)`
4120+
4121+
<!-- YAML
4122+
added: REPLACEME
4123+
-->
4124+
4125+
> Stability: 1 - Experimental
4126+
4127+
* `prefix` {string|Buffer|URL}
4128+
* `options` {string|Object}
4129+
* `encoding` {string} **Default:** `'utf8'` (or `'buffer'` if `prefix` is a `Buffer`)
4130+
* `callback` {Function}
4131+
* `err` {Error}
4132+
* `file` {Object}
4133+
* `path` {string|Buffer} The path of the created file.
4134+
* `fd` {integer} A file descriptor for the created file, opened for
4135+
reading and writing.
4136+
4137+
Creates and opens a unique temporary file.
4138+
4139+
Generates six random characters to be appended behind a required `prefix` to
4140+
create a unique temporary file. Due to platform inconsistencies, avoid trailing
4141+
`X` characters in `prefix`. Some platforms, notably the BSDs, can return more
4142+
than six random characters, and replace trailing `X` characters in `prefix`
4143+
with random characters.
4144+
4145+
The file is created and opened in a single operation, so another process cannot
4146+
create a file with the same name in between. On POSIX systems, the file is only
4147+
readable and writable by its owner.
4148+
4149+
The optional `options` argument can be a string specifying an encoding, or an
4150+
object with an `encoding` property specifying the character encoding to use for
4151+
the `path` passed to the callback.
4152+
4153+
```mjs
4154+
import { mkstemp, write, close } from 'node:fs';
4155+
import { join } from 'node:path';
4156+
import { tmpdir } from 'node:os';
4157+
4158+
mkstemp(join(tmpdir(), 'foo-'), (err, file) => {
4159+
if (err) throw err;
4160+
console.log(file.path);
4161+
// Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
4162+
write(file.fd, 'some data', (err) => {
4163+
if (err) throw err;
4164+
close(file.fd, (err) => {
4165+
if (err) throw err;
4166+
});
4167+
});
4168+
});
4169+
```
4170+
4171+
The file is not removed automatically. It is the caller's responsibility to
4172+
close the file descriptor and to remove the file when it is no longer needed.
4173+
4174+
As with [`fs.mkdtemp()`][], the random characters are appended directly to
4175+
`prefix`. To create a file _within_ a directory, `prefix` must end with a
4176+
trailing platform-specific path separator (`require('node:path').sep`) or
4177+
include the beginning of the file name.
4178+
40674179
### `fs.open(path[, flags[, mode]], callback)`
40684180
40694181
<!-- YAML
@@ -6532,6 +6644,31 @@ with the [`using`][] syntax.
65326644
The optional `options` argument can be a string specifying an encoding, or an
65336645
object with an `encoding` property specifying the character encoding to use.
65346646
6647+
### `fs.mkstempSync(prefix[, options])`
6648+
6649+
<!-- YAML
6650+
added: REPLACEME
6651+
-->
6652+
6653+
> Stability: 1 - Experimental
6654+
6655+
* `prefix` {string|Buffer|URL}
6656+
* `options` {string|Object}
6657+
* `encoding` {string} **Default:** `'utf8'` (or `'buffer'` if `prefix` is a `Buffer`)
6658+
* Returns: {Object}
6659+
* `path` {string|Buffer} The path of the created file.
6660+
* `fd` {integer} A file descriptor for the created file, opened for reading
6661+
and writing.
6662+
6663+
Synchronously creates and opens a unique temporary file.
6664+
6665+
For detailed information, see the documentation of the asynchronous version of
6666+
this API: [`fs.mkstemp()`][].
6667+
6668+
The optional `options` argument can be a string specifying an encoding, or an
6669+
object with an `encoding` property specifying the character encoding to use for
6670+
the returned `path`.
6671+
65356672
### `fs.openAsBlobSync(path[, options])`
65366673
65376674
<!-- YAML
@@ -9457,6 +9594,7 @@ the file contents.
94579594
[`fs.lutimes()`]: #fslutimespath-atime-mtime-callback
94589595
[`fs.mkdir()`]: #fsmkdirpath-options-callback
94599596
[`fs.mkdtemp()`]: #fsmkdtempprefix-options-callback
9597+
[`fs.mkstemp()`]: #fsmkstempprefix-options-callback
94609598
[`fs.open()`]: #fsopenpath-flags-mode-callback
94619599
[`fs.openAsBlob()`]: #fsopenasblobpath-options
94629600
[`fs.opendir()`]: #fsopendirpath-options-callback

‎doc/api/vfs.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,7 @@ signatures as their [`node:fs`][] counterparts:
374374
* `utimesSync(path, atime, mtime)`
375375
* `lutimesSync(path, atime, mtime)`
376376
* `mkdtempSync(prefix)`
377+
* `mkstempSync(prefix)`
377378
* `opendirSync(path[, options])`
378379
* `openAsBlob(path[, options])`
379380
* File-descriptor ops: `openSync`, `closeSync`, `readSync`, `writeSync`,
@@ -385,8 +386,8 @@ signatures as their [`node:fs`][] counterparts:
385386

386387
`readFile`, `writeFile`, `stat`, `lstat`, `readdir`, `realpath`, `readlink`,
387388
`access`, `open`, `close`, `read`, `write`, `rm`, `fstat`, `truncate`,
388-
`ftruncate`, `link`, `mkdtemp`, `opendir`. Each takes a Node.js-style
389-
callback `(err, ...result) => {}`.
389+
`ftruncate`, `link`, `mkdtemp`, `mkstemp`, `opendir`. Each takes a
390+
Node.js-style callback `(err, ...result) => {}`.
390391

391392
#### Promise API
392393

@@ -407,8 +408,8 @@ example();
407408
The promise namespace mirrors `fs.promises` and includes `readFile`,
408409
`writeFile`, `appendFile`, `stat`, `lstat`, `readdir`, `mkdir`, `rmdir`,
409410
`unlink`, `rename`, `copyFile`, `realpath`, `readlink`, `symlink`,
410-
`access`, `rm`, `truncate`, `link`, `mkdtemp`, `chmod`, `chown`, `lchown`,
411-
`utimes`, `lutimes`, `open`, `lchmod`, and `watch`.
411+
`access`, `rm`, `truncate`, `link`, `mkdtemp`, `mkstemp`, `chmod`, `chown`,
412+
`lchown`, `utimes`, `lutimes`, `open`, `lchmod`, and `watch`.
412413

413414
## The reserved root directory
414415

‎lib/fs.js‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3779,6 +3779,58 @@ function mkdtempDisposableSync(prefix, options) {
37793779
};
37803780
}
37813781

3782+
/**
3783+
* Creates and opens a unique temporary file.
3784+
* @param {string | Buffer | URL} prefix
3785+
* @param {string | { encoding?: string; }} [options]
3786+
* @param {(err?: Error, file?: { path: string | Buffer, fd: number }) => any} callback
3787+
* @returns {void}
3788+
*/
3789+
function mkstemp(prefix, options, callback) {
3790+
callback = makeCallback(typeof options === 'function' ? options : callback);
3791+
3792+
options = getOptions(options);
3793+
if (BufferIsBuffer(prefix)) {
3794+
options = { ...options, encoding: 'buffer' };
3795+
}
3796+
prefix = getValidatedPath(prefix, 'prefix');
3797+
warnOnNonPortableTemplate(prefix);
3798+
3799+
const h = vfsState.handlers;
3800+
if (h !== null && vfsResult(h.mkstemp(prefix, options), callback)) return;
3801+
3802+
const req = new FSReqCallback();
3803+
req.oncomplete = (err, result) => {
3804+
if (err) return callback(err);
3805+
callback(null, { path: result[0], fd: result[1] });
3806+
};
3807+
binding.mkstemp(prefix, options.encoding, req);
3808+
}
3809+
3810+
/**
3811+
* Synchronously creates and opens a unique temporary file.
3812+
* @param {string | Buffer | URL} prefix
3813+
* @param {string | { encoding?: string; }} [options]
3814+
* @returns {{ path: string | Buffer, fd: number }}
3815+
*/
3816+
function mkstempSync(prefix, options) {
3817+
options = getOptions(options);
3818+
if (BufferIsBuffer(prefix)) {
3819+
options = { ...options, encoding: 'buffer' };
3820+
}
3821+
prefix = getValidatedPath(prefix, 'prefix');
3822+
warnOnNonPortableTemplate(prefix);
3823+
3824+
const h = vfsState.handlers;
3825+
if (h !== null) {
3826+
const result = h.mkstempSync(prefix, options);
3827+
if (result !== undefined) return result;
3828+
}
3829+
3830+
const result = binding.mkstemp(prefix, options.encoding);
3831+
return { path: result[0], fd: result[1] };
3832+
}
3833+
37823834
/**
37833835
* Asynchronously copies `src` to `dest`. By
37843836
* default, `dest` is overwritten if it already exists.
@@ -4003,6 +4055,8 @@ module.exports = fs = {
40034055
mkdtemp,
40044056
mkdtempSync,
40054057
mkdtempDisposableSync,
4058+
mkstemp,
4059+
mkstempSync,
40064060
open,
40074061
openSync,
40084062
openAsBlob,

‎lib/internal/fs/promises.js‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2135,6 +2135,28 @@ async function mkdtemp(prefix, options) {
21352135
);
21362136
}
21372137

2138+
async function mkstemp(prefix, options) {
2139+
options = getOptions(options);
2140+
if (BufferIsBuffer(prefix)) {
2141+
options = { ...options, encoding: 'buffer' };
2142+
}
2143+
prefix = getValidatedPath(prefix, 'prefix');
2144+
warnOnNonPortableTemplate(prefix);
2145+
2146+
const h = vfsState.handlers;
2147+
if (h !== null) {
2148+
const promise = h.promisesMkstemp(prefix, options);
2149+
if (promise !== undefined) return await promise;
2150+
}
2151+
2152+
const result = await PromisePrototypeThen(
2153+
binding.mkstemp(prefix, options.encoding, kUsePromises),
2154+
undefined,
2155+
handleErrorFromBinding,
2156+
);
2157+
return { __proto__: null, path: result[0], handle: new FileHandle(result[1]) };
2158+
}
2159+
21382160
async function mkdtempDisposable(prefix, options) {
21392161
options = getOptions(options);
21402162

@@ -2386,6 +2408,7 @@ module.exports = {
23862408
realpath,
23872409
mkdtemp,
23882410
mkdtempDisposable,
2411+
mkstemp,
23892412
writeFile,
23902413
appendFile,
23912414
readFile,

‎lib/internal/fs/utils.js‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -965,12 +965,14 @@ const validateBufferArray = hideStackFrames((buffers, propName = 'buffers') => {
965965
let nonPortableTemplateWarn = true;
966966

967967
function warnOnNonPortableTemplate(template) {
968-
// Template strings passed to the mkdtemp() family of functions should not
969-
// end with 'X' because they are handled inconsistently across platforms.
968+
// Template strings passed to the mkdtemp() and mkstemp() families of
969+
// functions should not end with 'X' because they are handled inconsistently
970+
// across platforms.
970971
if (nonPortableTemplateWarn &&
971972
((typeof template === 'string' && StringPrototypeEndsWith(template, 'X')) ||
972973
(typeof template !== 'string' && TypedArrayPrototypeAt(template, -1) === 0x58))) {
973-
process.emitWarning('mkdtemp() templates ending with X are not portable. ' +
974+
process.emitWarning('mkdtemp() and mkstemp() templates ending with X are ' +
975+
'not portable. ' +
974976
'For details see: https://nodejs.org/api/fs.html');
975977
nonPortableTemplateWarn = false;
976978
}

‎lib/internal/vfs/file_system.js‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -615,8 +615,19 @@ class VirtualFileSystem {
615615
}
616616

617617
/**
618-
* Converts a mkdtemp prefix to a provider-relative one, keeping a
619-
* trailing separator.
618+
* Creates and opens a unique temporary file synchronously.
619+
* @param {string} prefix The prefix for the temp file
620+
* @returns {{ path: string, fd: number }} The full path and a file descriptor
621+
*/
622+
mkstempSync(prefix) {
623+
const filePath = this.#toProviderPrefix(prefix) + randomSuffix();
624+
const handle = this[kProvider].openSync(filePath, 'wx+', 0o600);
625+
return { path: this.#toMountedPath(filePath), fd: openVirtualFd(handle) };
626+
}
627+
628+
/**
629+
* Converts a mkdtemp or mkstemp prefix to a provider-relative one, keeping
630+
* a trailing separator.
620631
* @param {string} prefix The mounted prefix
621632
* @returns {string}
622633
*/
@@ -1058,6 +1069,25 @@ class VirtualFileSystem {
10581069
}
10591070
}
10601071

1072+
/**
1073+
* Creates and opens a unique temporary file asynchronously.
1074+
* @param {string} prefix The prefix for the temp file
1075+
* @param {object|Function} [options] Options or callback
1076+
* @param {Function} [callback] Callback (err, { path, fd })
1077+
*/
1078+
mkstemp(prefix, options, callback) {
1079+
if (typeof options === 'function') {
1080+
callback = options;
1081+
options = undefined;
1082+
}
1083+
try {
1084+
const file = this.mkstempSync(prefix);
1085+
process.nextTick(callback, null, file);
1086+
} catch (err) {
1087+
process.nextTick(callback, err);
1088+
}
1089+
}
1090+
10611091
/**
10621092
* Opens a directory asynchronously.
10631093
* @param {string} dirPath The directory path
@@ -1309,6 +1339,16 @@ class VirtualFileSystem {
13091339
return toMountedPath(dirPath);
13101340
},
13111341

1342+
async mkstemp(prefix) {
1343+
const filePath = toProviderPrefix(prefix) + randomSuffix();
1344+
const handle = provider.openSync(filePath, 'wx+', 0o600);
1345+
return {
1346+
__proto__: null,
1347+
path: toMountedPath(filePath),
1348+
fd: openVirtualFd(handle),
1349+
};
1350+
},
1351+
13121352
async chmod(filePath, mode) {
13131353
const providerPath = toProviderPath(filePath);
13141354
provider.chmodSync(providerPath, mode);

0 commit comments

Comments
 (0)