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
相關用法
- Node.js GM blur()用法及代碼示例
- Node.js GM drawRectangle()用法及代碼示例
- Node.js GM sharpen()用法及代碼示例
- Node.js GM drawPolyline()用法及代碼示例
- Node.js GM drawEllipse()用法及代碼示例
- Node.js GM drawCircle()用法及代碼示例
- Node.js GM drawPolygon()用法及代碼示例
注:本文由純淨天空篩選整理自shuraj1825大神的英文原創作品 Node.js | fs.mkdirSync() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。