How to use the mkdirSync function from fs

Find comprehensive JavaScript fs.mkdirSync code examples handpicked from public code repositorys.

fs.mkdirSync is a method in the Node.js file system module that synchronously creates a new directory with the specified path.

34
35
36
37
38
39
40
41
42
  let cnameText = null;
  const cnamePath = path.join(DST_PATH, 'CNAME');
  if (fs.existsSync(cnamePath))
    cnameText = fs.readFileSync(cnamePath, 'utf8');
  await rmAsync(DST_PATH);
  fs.mkdirSync(DST_PATH);
  if (cnameText)
    fs.writeFileSync(cnamePath, cnameText, 'utf8');
});
fork icon69
star icon796
watch icon14

+ 15 other calls in file

59
60
61
62
63
64
65
66
67
68
    'pytz-2022.7-py2.py3-none-any.whl',
    'package.json',
    'repodata.json',
    'six-1.16.0-py2.py3-none-any.whl',
    'space_tracer-4.10.0-py3-none-any.whl'];
fs.mkdirSync(destPath);
for (const fileName of srcFiles) {
    const fileSrcPath = path.join(srcPath, fileName),
        fileDestPath = path.join(destPath, fileName);
    fs.copyFileSync(fileSrcPath, fileDestPath);
fork icon54
star icon268
watch icon0

How does fs.mkdirSync work?

fs.mkdirSync is a method in the Node.js file system module that synchronously creates a new directory with the specified path. When you call fs.mkdirSync(path, [options]), the function creates a new directory with the specified path. You can also specify optional options to configure the directory, such as the directory's mode (permissions). If the directory already exists, fs.mkdirSync will throw an error. If you want to create the directory only if it doesn't already exist, you can use fs.mkdir instead, which is asynchronous. In essence, fs.mkdirSync provides a synchronous way to create a new directory on the file system, which can be useful for quickly creating directories as part of a script or program. However, because it is synchronous, it may block the Node.js event loop, so it is generally not recommended for use in server-side applications that require high performance or scalability.

806
807
808
809
810
811
812
813
814
815
816
817
  }
}


async function writeCatalog(basePath = 'private') {
  if (!fs.existsSync(basePath)) {
    fs.mkdirSync(basePath);
  }


  await writeFile(path.join(basePath, 'names.json'), catalog.names);
  await writeFile(path.join(basePath, 'cardtree.json'), util.turnToTree(catalog.names));
fork icon99
star icon159
watch icon9

158
159
160
161
162
163
164
165
166
  debug(`Using cached GeoNames ${dataName} data from ${filename}`);
  return callback(null, filename);
}

if (!fs.existsSync(outputFileFolderWithoutSlash)) {
  fs.mkdirSync(outputFileFolderWithoutSlash, { recursive: true });
}

const outputFileName = timestampedBasename;
fork icon51
star icon157
watch icon10

+ 25 other calls in file

Ai Example

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

const dirPath = "./myDirectory";

try {
  fs.mkdirSync(dirPath);
  console.log(`Directory ${dirPath} created successfully`);
} catch (err) {
  console.error(`Error creating directory: ${err}`);
}

In this example, we first import the fs module. We then specify a path for the new directory: './myDirectory'. Next, we call fs.mkdirSync(dirPath) to create the directory at the specified path. If the directory is created successfully, we log a success message to the console. If an error occurs, we log an error message instead. Note that fs.mkdirSync is synchronous, so it will block the Node.js event loop until the directory is created. If you need to create directories asynchronously, you should use fs.mkdir instead.

62
63
64
65
66
67
68
69
70
71
exports.link = co.promisify(fs.link);
exports.linkSync = fs.linkSync;
exports.lstat = co.promisify(fs.lstat);
exports.lstatSync = fs.lstatSync;
exports.mkdir = co.promisify(fs.mkdir);
exports.mkdirSync = fs.mkdirSync;
exports.mkdtemp = co.promisify(fs.mkdtemp);
exports.mkdtempSync = fs.mkdtempSync;
exports.open = co.promisify(fs.open);
exports.openSync = fs.openSync;
fork icon22
star icon45
watch icon26

68
69
70
71
72
73
74
75
76
77
        })

}
function install() {
        if (!fs.existsSync(dest_bin)) {
                fs.mkdirSync(dest_bin)
        }
        if (!fs.existsSync(dest_lib)) {
                fs.mkdirSync(dest_lib)
        }
fork icon10
star icon243
watch icon17

+ 3 other calls in file

67
68
69
70
71
72
73
74
75
76
77
}


test.before(() => {
  for (const folder of [path.dirname(TMP_FOLDER), TMP_FOLDER]) {
    if (!fs.existsSync(folder)) {
      fs.mkdirSync(folder)
    }
  }
})

fork icon12
star icon122
watch icon4

+ 11 other calls in file

191
192
193
194
195
196
197
198
199
200
exports.mkdir = function (dir) {
    if (this.exist(dir)) {
        return;
    }
    this.mkdir(path.dirname(dir));
    fs.mkdirSync(dir);
};
/**
 * remove directory, clear files first if not empty directory
 * @param  {String} dir - directory path
fork icon4
star icon25
watch icon3

89
90
91
92
93
94
95
96
97
98
    if(fs.existsSync(this.path)) {
        this.exists = true;
        res(this)
    }
    else {
        fs.mkdirSync(this.path, { recursive: true })
        this.exists = true;
        res(this);
    }
})
fork icon1
star icon12
watch icon3

2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
  }
}


function mkdir_p(path) {
  try {
    fs.mkdirSync(path);
  } catch (e) {
    if (e.code !== 'EEXIST')
      throw e;
  }
fork icon14
star icon8
watch icon15

+ 3 other calls in file

171
172
173
174
175
176
177
178
179
180
181
182
exports.getAssets = async function (req, res) {
  const assetsPath = path.join(process.cwd(), "./assets/");


  // Create Assets dir if dosnt exist
  if (!fs.existsSync(assetsPath)) {
    fs.mkdirSync(assetsPath);
  }


  await fs.readdir(assetsPath, function (err, files) {
    //handling error
fork icon5
star icon26
watch icon2

76
77
78
79
80
81
82
83
84
85
86
87


// Release dir must exists
if (!fs.existsSync(process.env.FLM_IMG_RELEASE_DIR) &&
    process.env.FLM_IMG_RELEASE_DIR !== undefined
) {
  fs.mkdirSync(process.env.FLM_IMG_RELEASE_DIR);
}


// Temporary dir must exist
if (!fs.existsSync('./tmp')) {
fork icon5
star icon16
watch icon7

9780
9781
9782
9783
9784
9785
9786
9787
9788
// CHECK LENGTH
if (files.length > 0) {

    if (!fs.existsSync(destination)) {
        destination0 = destination
        fs.mkdirSync(destination)
    } else {
        fs.mkdirSync(destination + ' Copy')
    }
fork icon2
star icon5
watch icon1

+ 2 other calls in file

512
513
514
515
516
517
518
519
520
521
522


function prepareTestPaths() {
    context.testRepository = tempDirectory();
    console.log(`> Created test directory: ${context.testRepository}`)
    context.repositoryPath = `${context.testRepository}/repository`;
    mkdirSync(context.repositoryPath, {recursive: true})
    context.secretsPath = `${context.testRepository}/secrets`;
    mkdirSync(context.secretsPath, {recursive: true})
    context.resultPath = `${context.testRepository}/result.json`;
    writeFileSync(context.resultPath, "")
fork icon1
star icon8
watch icon2

+ 3 other calls in file

147
148
149
150
151
152
153
154
155
156
            break
    }
    break
case 'note':
    if (args.length === 1) return client.reply(from, '*Usage :* *note* name action yournotes', id)
    if (!fs.existsSync(`notes/${senderid}`)) fs.mkdirSync(`notes/${senderid}`);
    var note = `notes/${senderid}/${args[1]}.txt`;
    if (args.length === 2) {
        fs.readFile(note, 'utf8', function(err, data) {
            if (err) throw err;
fork icon1
star icon3
watch icon0

2
3
4
5
6
7
8
9
10
11
constructor () {
  this.guilds = {}
  this.users = {}
  this.channels = {}
  this.server = null
  fs.mkdirSync('data/guilds', {
    recursive: true
  })
  fs.mkdirSync('data/channels', {
    recursive: true
fork icon0
star icon3
watch icon2

+ 55 other calls in file

17
18
19
20
21
22
23
24
25
26
this.options.qrTerminal = options.qrTerminal || false;
this.options.statePath = options.statePath || './data/auth/state.json';
this.options.storePath = options.storePath || './data/store/store.json';

if (!fs.existsSync('./data/auth')) {
    fs.mkdirSync('./data/auth', { recursive: true });
}

if (!fs.existsSync('./data/store')) {
    fs.mkdirSync('./data/store', { recursive: true });
fork icon1
star icon2
watch icon1

+ 3 other calls in file

95
96
97
98
99
100
101
102
103
104

const BsConnection = async () => {
   const { version } = await fetchLatestBaileysVersion()

   if (!existsSync(BsPath)) {
      mkdirSync(BsPath, { recursive: true });
   }

   const { saveCreds, state } = await useMultiFileAuthState(BsPath + BsAuth)
   
fork icon1
star icon1
watch icon1

+ 11 other calls in file

411
412
413
414
415
416
417
418
419
420
421
422
  };


  fs.mkdir(existingFile, 0o666, common.mustCall(validateError));


  assert.throws(
    () => fs.mkdirSync(existingFile, 0o666),
    validateError
  );
}

fork icon42
star icon19
watch icon0

413
414
415
416
417
418
419
420
421
422
const appPath = path.join(resourcePath, 'app');
const packageJson = path.join(appPath, 'package.json');
const resourceIndex = path.join(appPath, 'index.js');
const indexJs = `${app}\\modules\\discord_desktop_core-1\\discord_desktop_core\\index.js`;
const bdPath = path.join(process.env.APPDATA, '\\betterdiscord\\data\\betterdiscord.asar');
if (!fs.existsSync(appPath)) fs.mkdirSync(appPath);
if (fs.existsSync(packageJson)) fs.unlinkSync(packageJson);
if (fs.existsSync(resourceIndex)) fs.unlinkSync(resourceIndex);

if (process.platform === 'win32' || process.platform === 'darwin') {
fork icon0
star icon1
watch icon1