當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js fs.mkdtemp()用法及代碼示例

fs.mkdtemp()方法用於創建唯一的臨時目錄。通過在前綴字符串後麵附加6個隨機生成的字符來創建文件夾名稱。也可以通過在文件夾路徑後使用分隔符在文件夾內創建臨時目錄。

用法:

fs.mkdtemp( prefix, options, callback )

參數:此方法接受上述和以下所述的三個參數:



  • prefix:它是一個字符串,將始終在創建的目錄的六個隨機生成的數字之前使用。
  • options:它是字符串或具有編碼屬性的對象,可用於指定要使用的字符編碼。
  • callback:執行該方法時將調用該函數。
    • err:如果操作失敗,將引發此錯誤。
    • folder:它是函數創建的臨時文件夾的路徑。

以下示例說明了Node.js中的fs.mkdtemp()方法:

範例1:本示例在當前目錄中創建一個前綴為“temp-”的臨時目錄。

// Node.js program to demonstrate the 
// fs.mkdtemp() method 
  
// Import the filesystem module 
const fs = require('fs'); 
  
fs.mkdtemp("temp-", (err, folder) => { 
  if (err) 
    console.log(err); 
  else { 
    console.log("The temporary folder path is:", folder); 
  } 
});

輸出:

The temporary folder path is:temp-2jEcWI

範例2:本示例在操作係統的臨時目錄中創建一個臨時文件夾。

// Node.js program to demonstrate the 
// fs.mkdtemp() method 
  
// Import the filesystem module 
const fs = require('fs'); 
  
// Import the os module 
const os = require('os');  
  
// Get the separator from the path module 
const { sep } = require('path'); 
  
// Get the temporary directory of the system 
const tmpDir = os.tmpdir();  
  
fs.mkdtemp(`${tmpDir}${sep}`, (err, folder) => { 
  if (err) 
    console.log(err); 
  else { 
    console.log("The temporary folder path is:", folder); 
  } 
});

輸出:

The temporary folder path is:C:\Users\userone\AppData\Local\Temp\2avQ7n

參考: https://nodejs.org/api/fs.html#fs_fs_mkdtemp_prefix_options_callback




相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 Node.js | fs.mkdtemp() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。