Node.js fs.mkdirSync() 方法
fs.mkdirSync() 方法是fs模块的内置应用程序编程接口,它提供了一个 API,用于以与标准POSIX函数紧密建模的方式与文件系统交互。
fs.mkdirSync() 方法用于同步创建目录。
句法:
fs.mkdirSync( path, options )
参数:此方法接受上面提到的两个参数,如下所述:
- path:要创建目录的路径。它可以是字符串、缓冲区等。
- options:它是一个可选参数,它确定如何创建目录,如递归等。
返回值:返回undefined 。
下面的例子说明了 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