当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Node.js fs.mkdtemp(prefix[, options], callback)用法及代码示例

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

历史
版本变化
v18.0.0

将无效回调传递给 callback 参数现在会抛出 ERR_INVALID_ARG_TYPE 而不是 ERR_INVALID_CALLBACK

v16.5.0、v14.18.0

prefix 参数现在接受一个空字符串。

v10.0.0

callback 参数不再是可选的。不通过它将在运行时抛出TypeError

v7.0.0

callback 参数不再是可选的。不通过它将发出带有 ID DEP0013 的弃用警告。

v6.2.1

callback 参数现在是可选的。

v5.10.0

添加于:v5.10.0


参数

创建一个唯一的临时目录。

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

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

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

import { mkdtemp } from 'node: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
});

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

import { tmpdir } from 'node:os';
import { mkdtemp } from 'node:fs';

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

// This method is *INCORRECT*:
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*:
import { sep } from 'node:path';
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.
});

相关用法


注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 fs.mkdtemp(prefix[, options], callback)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。