How to use the mkdir function from fs-extra

Find comprehensive JavaScript fs-extra.mkdir code examples handpicked from public code repositorys.

fs-extra.mkdir is a method in the fs-extra library used in Node.js that creates a new directory.

1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
// Clear the previous output folder if it exists,
// or create the output directory first if it doesn't.
if (pathExists(outputLocation)) {
  await fs.emptyDir(outputLocation)
} else {
  await fs.mkdir(outputLocation, { recursive: true })
}

return new Promise(function (resolve, reject) {
  // Loop through files and convert with Pandoc
fork icon39
star icon105
watch icon0

31
32
33
34
35
36
37
38
39
40
// read package.json
const pkg = await fs.readJSON(path.resolve(process.cwd(), "package.json"));
// remove old app folder
await rimraf(path.resolve(process.cwd(), `${appDistributionName}.app`));
// create app folder
await fs.mkdir(path.resolve(process.cwd(), `${appDistributionName}.app`));
await fs.mkdir(
  path.resolve(process.cwd(), `${appDistributionName}.app`, "Contents")
);
await fs.mkdir(
fork icon15
star icon187
watch icon0

+ 4 other calls in file

How does fs-extra.mkdir work?

fs-extra.mkdir is a method in the fs-extra library used in Node.js that creates a new directory. Here's how it works:

  1. The fs-extra library extends the built-in fs module in Node.js with additional functionality, including the ability to create directories using the mkdir method.

  2. The mkdir method takes two arguments: the path to the new directory and an optional options object.

  3. By default, fs-extra.mkdir will create the directory with read/write/execute permissions for the current user, but you can override these defaults using the options object.

  4. The options object can include properties like recursive (a boolean indicating whether to create parent directories if they don't already exist), mode (an integer representing the file permissions), and fs (a custom fs implementation to use instead of the default Node.js fs module).

  5. When you call fs-extra.mkdir, it will create the new directory at the specified path, along with any necessary parent directories if recursive is set to true.

  6. If the directory already exists, fs-extra.mkdir will throw an error by default, but you can override this behavior using the force option.

  7. The force option will silently do nothing if the directory already exists, rather than throwing an error.

Here is an example of using fs-extra.mkdir to create a new directory:

javascript
const fs = require("fs-extra"); fs.mkdir("./my-directory", (err) => { if (err) { console.error(err); } else { console.log("Directory created successfully."); } });

In this example, we use fs-extra.mkdir to create a new directory called "my-directory" in the current working directory.

If the directory is created successfully, the callback function will log "Directory created successfully." to the console.

If there is an error creating the directory, the callback function will log the error to the console.

Note that fs-extra.mkdir is an asynchronous method, so it requires a callback function to handle errors and other results. You can also use async/await or promises to work with fs-extra.mkdir in a more synchronous style.

64
65
66
67
68
69
70
71
72
73
    return;
}

const extPackSrcFolder = theiaExtension(extPackNameAndVersion);
if (!fs.existsSync(extPackSrcFolder)) {
    await fs.mkdir(extPackSrcFolder);
}

const extPack = {};
extPack.name = packName;
fork icon32
star icon58
watch icon15

97
98
99
100
101
102
103
104
105
106
107
108


const initForTypeScript = async (root, rootFolder) => {
  output.info("Initializing for TypeScript...");


  if (!fs.existsSync("app")) {
    fs.mkdir("app", (err) => {
      if (err) throw err;
    });
  }

fork icon5
star icon36
watch icon0

Ai Example

1
2
3
4
5
6
7
8
9
10
const fs = require("fs-extra");

// Create a new directory
fs.mkdir("./my-directory", (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log("Directory created successfully.");
  }
});

In this example, we use fs-extra.mkdir to create a new directory called "my-directory" in the current working directory. If the directory is created successfully, the callback function will log "Directory created successfully." to the console. If there is an error creating the directory, the callback function will log the error to the console. Note that fs-extra.mkdir is an asynchronous method, so it requires a callback function to handle errors and other results. You can also use async/await or promises to work with fs-extra.mkdir in a more synchronous style.

3
4
5
6
7
8
9
10
11
12
13
14
const hljs = require('highlight.js'); // https://highlightjs.org/
// const eleventyToc = require('./eleventy-toc.js');
const pluginTOC = require('eleventy-plugin-toc');


function buildSass(srcDir, destDir) {
  fs.mkdir(destDir, { recursive: true });


  // Compile all the .scss files in ./src/_sass
  fs.readdir(srcDir, (_err, files) => {
    files.forEach((file) => {
fork icon9
star icon32
watch icon2

+ 8 other calls in file

230
231
232
233
234
235
236
237
238
239
- fs.close():关闭文件描述符
- fs.copyFile():复制文件
- fs.createReadStream():创建可读的文件流
- fs.createWriteStream():创建可写文件流
- fs.link():创建指向文件的新硬链接
- fs.mkdir(): 新建一个文件夹
- fs.mkdtemp():创建一个临时目录
- fs.open():设置文件模式
- fs.readdir():读取目录的内容
- fs.readFile():读取文件的内容。有关:fs.read()
fork icon0
star icon12
watch icon1

+ 13 other calls in file

357
358
359
360
361
362
363
364
365
366
constructor(opts){
    super(opts);
    var store=this;
    var fileName='sessions/local-sessions.dump';
    Promise.resolve().then(function(){
        return fs.mkdir('sessions').then(function(){
            console.log('sessions dir created');
        },function(err){
            if(err.code!='EEXIST'){
                console.log('ERROR in mkdir sessions');
fork icon3
star icon4
watch icon10

+ 11 other calls in file

34
35
36
37
38
39
40
41
42
43
};
var userDir = path.join(__dirname,".testUserHome");
var testFlow = [{"type":"tab","id":"d8be2a6d.2741d8","label":"Sheet 1"}];
beforeEach(function(done) {
    fs.remove(userDir,function(err) {
        fs.mkdir(userDir,done);
    });
});
afterEach(function(done) {
    fs.remove(userDir,done);
fork icon1
star icon4
watch icon0

652
653
654
655
656
657
658
659
660
661
662
        .catch(cb);
};


const writeTempRepoModules = function (repo, cb) {
    const fullPath = createPath();
    return fs.mkdir(fullPath, 0o0777, function (err) {
        if (err) {
            console.error(err);
            return cb({
                error: "Failed to package the files for compiling.",
fork icon0
star icon2
watch icon3

+ 29 other calls in file

779
780
781
782
783
784
785
786
787
788
    tempDownloadPath,
    "output-log.json"
);
outputBucket = token.resultBucket;
outputKey = token.resultPath;
return fs.mkdir(
    tempDownloadPath,
    function (err) {
        if (err) {
            cleanupWithFail(
fork icon0
star icon2
watch icon3

+ 9 other calls in file

244
245
246
247
248
249
250
251
252
253
	console.log();
	console.log(content);
}

if (!this.options.dryRun) {
	await mkdir(this.docFolderPath, { recursive: true });
	await writeFile(filePath, content, 'utf8');
	console.log(pico.yellow(`🥨 --> Lint output file for packages`));
	exec(`npx eslint --fix ${filePath}`);
}
fork icon0
star icon2
watch icon3

+ 31 other calls in file

228
229
230
231
232
233
234
235
236
237
if (this.options.dryRun) {
	console.log(pico.yellow(`🥨 --> Orion would write following content in ${fileRelativePath}`));
	console.log();
	console.log(fileContent);
} else {
	await fs.mkdir(path.resolve(this.typesPath, path.dirname(filePath)), { recursive: true });
	await fs.writeFile(filePath, fileContent, 'utf8');
}

successFiles.push(filePath);
fork icon0
star icon2
watch icon3

+ 7 other calls in file

7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
    copyDir(dir.name)
  })
}

function mkDir (dir, target) {
  fs.mkdir(target, dir.mode, function (err) {
    if (err) return onError(err)
    // despite setting mode in fs.mkdir, doesn't seem to work
    // so we set it here.
    fs.chmod(target, dir.mode, function (err) {
fork icon0
star icon1
watch icon0

+ 8 other calls in file

69
70
71
72
73
74
75
76
77
78
79
80
      }
   }
}


fse.exists("files").then((filesFolderExists) => {
   if (!filesFolderExists) fse.mkdir("files");
})


const wss = new WebSocket.Server({ port: port });

fork icon0
star icon0
watch icon1

+ 8 other calls in file

524
525
526
527
528
529
530
531
532
533
//   Upload files 
//
if(req.files){
    // console.log('uploading');
    //FOR mariadb10.2.8
    fs.mkdir(__dirname+'/tmpFile/'+arg1,0o755, function(err){
    //fs.mkdir('/Users/miaot2/html_learning/SAIP/Backend/tmpFile/'+arg1,0o755, function(err){
        if(err) {
            logger.error({
                level: 'error',
fork icon0
star icon0
watch icon3

+ 89 other calls in file

101
102
103
104
105
106
107
108
109
110
file = file.split('.')[0];
const libComponentRoot = path.join(libRoot, file);
const libComponentPackageRoot = path.join(libRoot, file, 'package.json');

// Create folder by component file name and write json
await fse.mkdir(libComponentRoot);
await fse.writeJson(
  libComponentPackageRoot,
  {
    private: true,
fork icon0
star icon0
watch icon1

+ 2 other calls in file

55
56
57
58
59
60
61
62
63
64
const CreateFolder = (value) => {
  const path = value;

  fs.access(path, (error) => {
    if (error) {
      fs.mkdir(path, { recursive: true }, (error) => {
        if (error) {
          console.log(error);
          return false;
        }
fork icon0
star icon0
watch icon1

+ 3 other calls in file

118
119
120
121
122
123
124
125
126
127

product.save(function(err) {
    if (err) 
        return console.log(err);

        fs.mkdir('public/product_images/' +product._id, { recursive: true }); //thực hiện tạo folder có tên là id của sản phẩm

        fs.mkdirp('public/product_images/' +product._id + '/gallery', { recursive: true }); //thêm folder gellery sau cái folder trên

        fs.mkdirp('public/product_images/' +product._id + '/gallery/thumbs', { recursive: true }); //tương tự
fork icon0
star icon0
watch icon0

33
34
35
36
37
38
39
40
41
42
43
44
45
  })


  reloadProcesses()


  client.users.cache.forEach(async (user) => {
    if (!(await isExists(path.join(cache, user.id)))) return await fse.mkdir(path.join(cache, user.id))
  })
})


function rm(file, args) {
fork icon0
star icon0
watch icon0

function icon

fs-extra.readFileSync is the most popular function in fs-extra (9724 examples)