fs.mkdtemp(prefix[, options], callback)


创建唯一的临时目录。

生成六个随机字符,附加在所需的 prefix 后面以创建唯一的临时目录。 由于平台的不一致,请避免在 prefix 中尾随 X 字符。 某些平台,尤其是 BSD,可能返回六个以上的随机字符,并将 prefix 中的尾随 X 字符替换为随机字符。

创建的目录路径作为字符串传递给回调的第二个参数。

可选的 options 参数可以是指定编码的字符串,也可以是具有 encoding 属性(指定要使用的字符编码)的对象。

fs.mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {
  if (err) throw err;
  console.log(directory);
  // 打印: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
});

fs.mkdtemp() 方法会将六个随机选择的字符直接附加到 prefix 字符串。 例如,给定目录 /tmp,如果要在 /tmp 内创建临时目录,则 prefix 必须以平台特定的尾随路径分隔符(require('path').sep)结尾。

// 新临时目录的父目录
const tmpDir = os.tmpdir();

// 这个方法是*不正确的*:
fs.mkdtemp(tmpDir, (err, directory) => {
  if (err) throw err;
  console.log(directory);
  // 将打印类似于 `/tmpabc123` 的内容。
  // 在文件系统根目录创建一个新的临时目录,而不是在 /tmp 目录中。
});

// 这个方法是*正确的*:
const { sep } = require('path');
fs.mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
  if (err) throw err;
  console.log(directory);
  // 将打印类似于 `/tmp/abc123` 的内容。
  // 在 /tmp 目录中创建一个新的临时目录。
});

Creates a unique temporary directory.

Generates six random characters to be appended behind a required prefix to create a unique temporary directory. Due to platform inconsistencies, avoid trailing X characters in prefix. Some platforms, notably the BSDs, can return more than six random characters, and replace trailing X characters in prefix with random characters.

The created directory path is passed as a string to the callback's second parameter.

The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use.

fs.mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {
  if (err) throw err;
  console.log(directory);
  // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
});

The fs.mkdtemp() method will append the six randomly selected characters directly to the prefix string. For instance, given a directory /tmp, if the intention is to create a temporary directory within /tmp, the prefix must end with a trailing platform-specific path separator (require('path').sep).

// The parent directory for the new temporary directory
const tmpDir = os.tmpdir();

// This method is *INCORRECT*:
fs.mkdtemp(tmpDir, (err, directory) => {
  if (err) throw err;
  console.log(directory);
  // Will print something similar to `/tmpabc123`.
  // A new temporary directory is created at the file system root
  // rather than *within* the /tmp directory.
});

// This method is *CORRECT*:
const { sep } = require('path');
fs.mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
  if (err) throw err;
  console.log(directory);
  // Will print something similar to `/tmp/abc123`.
  // A new temporary directory is created within
  // the /tmp directory.
});