How to use the mkdir function from fs

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

fs.mkdir is a Node.js method that is used to create a new directory.

16
17
18
19
20
21
22
23
24
25
* fs.close(): 关闭文件描述符。
* fs.copyFile(): 拷贝文件。
* fs.createReadStream(): 创建可读的文件流。
* fs.createWriteStream(): 创建可写的文件流。
* fs.link(): 新建指向文件的硬链接。
* fs.mkdir(): 新建文件夹。
* fs.mkdtemp(): 创建临时目录。
* fs.open(): 设置文件模式。
* fs.readdir(): 读取目录的内容。
* fs.readFile(): 读取文件的内容。相关方法:fs.read()。
fork icon192
star icon570
watch icon16

+ 5 other calls in file

408
409
410
411
412
413
414
415
416
417
  assert.strictEqual(err.code, 'EEXIST');
  assert.strictEqual(err.syscall, 'mkdir');
  return true;
};

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

assert.throws(
  () => fs.mkdirSync(existingFile, 0o666),
  validateError
fork icon42
star icon19
watch icon0

How does fs.mkdir work?

fs.mkdir is a Node.js built-in method that creates a new directory with the specified path and permission mode. If the directory already exists, it will throw an error.

184
185
186
187
188
189
190
191
192
193
}
exports.exists = exists;
function mkdirp(path, mode, done) {
    if (mode === void 0) { mode = 511; }
    path = pathutil.resolve(path);
    fs.mkdir(path, mode, function (err) {
        if (!err)
            done(null);
        else if (err.code === 'ENOENT')
            mkdirp(pathutil.dirname(path), mode, function (err) {
fork icon3
star icon0
watch icon1

+ 5 other calls in file

117
118
119
120
121
122
123
124
125
126
	await fsPromises.mkdir(folder, {recursive: false});
}
/*
await fs.opendir(folder, async (err, dir) => {
	if (err) {
		// await fs.mkdir(folder, {recursive: false}, (err) => {
		// 	// Any callback that needs to happen on first folder create
		// 	// can happen here.
		// 	if (err) throw err;
		// });
fork icon0
star icon6
watch icon0

Ai Example

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

fs.mkdir("myFolder", (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log("Directory created successfully!");
  }
});

In this example, fs.mkdir is called with the path to the new directory to be created as the first argument, and a callback function as the second argument. The callback function is executed once the directory has been created, or if there was an error during the creation process. If there was an error, it will be logged to the console, and if the directory was created successfully, a success message will be logged.

9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
    }

})


// fs.mkdir(folder, {}, (err) => {

//     if (err) {
//         notification(err)
//     } else {
fork icon2
star icon5
watch icon1

14
15
16
17
18
19
20
21
22
23

var cb = f || function () {};
if (typeof mode === 'string') mode = parseInt(mode, 8);
p = path.resolve(p);

fs.mkdir(p, mode, function (er) {
    if (!er) {
        made = made || p;
        return cb(null, made);
    }
fork icon2
star icon1
watch icon2

714
715
716
717
718
719
720
721
722

let dialog = false;
if (target.data.default.all.trim().length) {
  const addons_path = path.join(target.data.default.all, 'addons');
  if (!fs.existsSync(addons_path)) {
    fs.mkdir(addons_path, () => {});
  } else {
    dialog = true;
  }
fork icon0
star icon6
watch icon2

245
246
247
248
249
250
251
252
253
254
255
256
}) => {
  // only write assets that have code. its possible some optimized assets can be empty.
  const eligible = assets.filter((asset) => asset.source);


  // make the dir
  await mkdir(path.resolve(cwd, dir, `./${FILE_ASSET_FOLDER}`), { recursive: true });


  const [css, writtenAssets] = await Promise.all([
    // css files
    Promise.all(eligible.map(async (asset) => {
fork icon9
star icon2
watch icon4

700
701
702
703
704
705
706
707
708
709
710
711


async function ensureDir(dirPath) {
    try {
        await fs.access(dirPath, fsConstants.R_OK | fsConstants.W_OK);
    } catch (err) {
        await fs.mkdir(dirPath);
    }
}


async function clearDir(rootPath) {
fork icon0
star icon1
watch icon1

21
22
23
24
25
26
27
28
29
30
// 验证格式
if (mailReg.test(req.body.username) && req.body.password.length >= 6 && req.body.password.length <= 16) {

    if (req.body.code === AES.get(req.cookies.wn)) {
        // 为用户创建个人目录
        fs.mkdir(`${userPath}/${req.body.username}`, (err) => {
            if (err) {
                fs.readFile(`${userPath}/${req.body.username}/info/userInfo.json`, 'utf-8',
                    (err, data) => {
                        if (err) {
fork icon0
star icon0
watch icon1

+ 3 other calls in file

42
43
44
45
46
47
48
49
50
51
  if (!fs.existsSync(path)) fs.writeFileSync(path, JSON.stringify({}));
    }
         
module.exports.run = async function({ api, event, args, Currencies }) {
  
  if (!fs.existsSync(pathDaily)) fs.mkdir(pathDaily);
	const listFile = fs.readdirSync(pathDaily);
  
  var checkDaily = JSON.parse(require("fs").readFileSync(__dirname + `/cache/daily.json`));
  let dataDaily = JSON.parse(fs.readFileSync(path));
fork icon0
star icon0
watch icon1

241
242
243
244
245
246
247
248
249
250
  // AKA - move
  clog.info('rename', oldPath, 'to', newPath)
  fs.rename(oldPath, newPath, cb)
},
mkdir(dir, cb=()=>{}){
  fs.mkdir(dir, { recursive: true }, cb)
},
path(x1, x2){
  if (!(x1 && x2)) return
  if (/^(\$|~)/.test(x1)) {
fork icon0
star icon0
watch icon1

+ 2 other calls in file

341
342
343
344
345
346
347
348
349
350
  if (!projects.get(projectId)) {
    throw new Error('No such projectId.');
  }
  const dest = path.join(UPLOADS_PATH, projectId);
  try {
    await fs.mkdir(dest);
  } catch (err) {}
  cb(null, dest);
} catch (err) {
  cb(err);
fork icon0
star icon0
watch icon1

220
221
222
223
224
225
226
227
228
229
230
231


/* DIRECTORIES */


function mkdir(affixes, callback) {
  var dirPath = generateName(affixes, 'd-');
  fs.mkdir(dirPath, 0700, function(err) {
    if (!err) {
      deleteDirOnExit(dirPath);
    }
    if (callback) {
fork icon0
star icon0
watch icon1

330
331
332
333
334
335
336
337
338
339
// gets a temporary filename
tmpName(opts, function _tmpNameCreated(err, name) {
  if (err) return cb(err);

  // create the directory
  fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) {
    if (err) return cb(err);

    cb(null, name, _prepareTmpDirRemoveCallback(name, opts));
  });
fork icon0
star icon0
watch icon1

576
577
578
579
580
581
582
583
584
585
else {
    fileName = "" + (splits[1] + '_' + splits[2] + '_' + message.filename);
}
diretorio_salva = 'arquivos/' + message.to + '/';
if (!fs.existsSync(diretorio_salva)) {
    fs.mkdir(diretorio_salva, function (err) {
        if (err) {
            console.log("Deu ruim...");
        }
        console.log("Diretório criado! =)");
fork icon0
star icon0
watch icon1

154
155
156
157
158
159
160
161
162
163
164
  });
}


function mkdir() {
  const fs = require('fs');
  fs.mkdir('fstemp0', () => {
    fs.rmdir('fstemp0', () => {});
  });
}

fork icon0
star icon0
watch icon0

+ 2 other calls in file

105
106
107
108
109
110
111
112
113
114
115
    permission: 'FileSystemWrite',
    resource: path.toNamespacedPath(path.join(blockedFolder, 'anyfile')),
  }));
}


// fs.mkdir
{
  assert.throws(() => {
    fs.mkdir(path.join(blockedFolder, 'any-folder'), (err) => {
      assert.ifError(err);
fork icon0
star icon0
watch icon0

+ 5 other calls in file