fs.mkdtemp(prefix[, options], callback)
曆史
版本 | 變化 |
---|---|
v18.0.0 | 將無效回調傳遞給 |
v16.5.0、v14.18.0 |
|
v10.0.0 |
|
v7.0.0 |
|
v6.2.1 |
|
v5.10.0 | 添加於:v5.10.0 |
參數
prefix
<string>options
<string>|<Object>encoding
<string> 默認:'utf8'
callback
<Function>
創建一個唯一的臨時目錄。
生成六個隨機字符,附加在所需的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.
});
相關用法
- Node.js fs.mkdtemp()用法及代碼示例
- Node.js fs.mkdtempSync()用法及代碼示例
- Node.js fs.mkdir()用法及代碼示例
- Node.js fs.mkdirSync()用法及代碼示例
- Node.js fs.mkdir(path[, options], callback)用法及代碼示例
- Node.js fs.filehandle.datasync()用法及代碼示例
- Node.js fs.chmod()用法及代碼示例
- Node.js fs.read()用法及代碼示例
- Node.js fs.Dirent.isFile()用法及代碼示例
- Node.js fs.Dir.closeSync()用法及代碼示例
- Node.js fs.fchmodSync()用法及代碼示例
- Node.js fs.symlink(target, path[, type], callback)用法及代碼示例
- Node.js fs.constants用法及代碼示例
- Node.js fs.fdatasync()用法及代碼示例
- Node.js fs.Dirent.isFIFO()用法及代碼示例
- Node.js fs.copyFile()用法及代碼示例
- Node.js fs.writeSync()用法及代碼示例
- Node.js fs.symlink()用法及代碼示例
- Node.js fs.truncate()用法及代碼示例
- Node.js fs.openSync()用法及代碼示例
- Node.js fs.filehandle.write()用法及代碼示例
- Node.js fs.fdatasyncSync()用法及代碼示例
- Node.js fs.filehandle.sync()用法及代碼示例
- Node.js fs.fsyncSync()用法及代碼示例
- Node.js fs.Dirent.isDirectory()用法及代碼示例
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 fs.mkdtemp(prefix[, options], callback)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。