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


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

fs.mkdirSync() 方法是 fs 模塊的內置應用程序編程接口,它提供了一個 API,用於以與標準 POSIX 函數密切建模的方式與文件係統交互。 fs.mkdirSync() 方法用於同步創建目錄。

用法:

fs.mkdirSync( path, options )

參數:此方法接受上麵提到並在下麵描述的兩個參數:

  • path:要創建目錄的路徑。它可以是字符串、緩衝區等。
  • options:它是一個可選參數,用於確定如何遞歸地創建目錄等。

返回值:它返回未定義。

下麵的例子說明了在 Node.js 中 fs.mkdirSync() 方法的使用:



範例1:


// Node.js program to demonstrate the
// fs.mkdirSync() method
   
const fs = require("fs");
   
const path = require("path");
   
// Using fs.exists() method to 
// check that the directory exists or not
console.log("Checking for directory " 
        + path.join(__dirname, "Geeks"));
fs.exists(path.join(__dirname, "Geeks"), exists => {
  console.log(exists ? "The directory already exists" 
                    :"Not found!");
});
   
// Using fs.mkdirSync() method
// to create the directory
fs.mkdirSync(path.join(__dirname, "Geeks"));
   
// Using fs.exists() method to
// check that the directory exists or not
fs.exists(path.join(__dirname, "Geeks"), exists => {
  console.log(exists ? "The directory already exists" 
                    :"Not found!");
});

輸出:

Checking for directory c:\Users\Suraj\node\Geeks
Not found!
The directory already exists

範例2:


// Node.js program to demonstrate the
// fs.mkdirSync() method
  
const fs = require("fs");
  
const path = require("path");
  
// Using fs.exists() method to
// check that the directory exists or not
console.log("Checking for directory" 
        + path.join(__dirname, "Tisu"));
fs.exists(path.join(__dirname, "Tisu"), exists => {
  console.log(exists ? "The directory already exists"
                         :"Not found!");
});
  
// Using fs.mkdirSync() method
// to create the directory recursively
fs.mkdirSync(path.join(__dirname, "Tisu"), true);
  
// Using fs.exists() method to
// check that the directory exists or not
fs.exists(path.join(__dirname, "Tisu"), exists => {
  console.log(exists ? "The directory already exists" 
                    :"Not found!");
});

輸出:

Checking for directory c:\Users\Suraj\node\Tisu
Not found!
The directory already exists

注意:上麵的程序將通過使用node index.js命令。

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




相關用法


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