Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use FS to make a folder automatically?

I'm trying to use code to read an array and create folders using the name as one of the parameters if that name doesn't exist. I've been using fs to make a simple loop, like so

var streamsRepository = streamsRepositoryFactory(__dirname + '/streams.json');
var obj = streamsRepository.streams[i];
var i;

for(i = 0; i < streamsRepository.streams.length; i++) {
    var obj = streamsRepository.streams[i];

console.log('Folder '+obj.key+' is Created');


    if (!fs.existsSync('../audio/'+obj.key)){
        fs.mkdirSync('../audio/'+obj.key);

    }
}

But every time I keep getting the message.

Folder AAAA is Created
fs.js:796
  return binding.mkdir(pathModule._makeLong(path),
                 ^
Error: ENOENT: no such file or directory, mkdir '../audio/AAAA'
like image 829
David Avatar asked Jul 22 '15 01:07

David


People also ask

How do I create a folder in fs?

Create a new folderUse fs. mkdir() or fs. mkdirSync() or fsPromises. mkdir() to create a new folder.

Which of the following methods in the fs module is used for creating a directory?

Creating Permanent Directories with fs. mkdir Family of Functions. To create permanent directories, we can use the mkdir function to create them asynchronously.

How do you create a folder if it doesn't exist NodeJS?

The best solution would be to use the npm module called node-fs-extra. It has a method called mkdir which creates the directory you mentioned. If you give a long directory path, it will create the parent folders automatically.

Which method helps us to create a directory in node js using the fs module?

mkdir() Method - GeeksforGeeks.


1 Answers

Have a test below

'use strict';
var fs = require('fs');
// fs.mkdirSync('folda'); // success
fs.mkdirSync('/parent-not-exists/folda'); 
// Failed,if parent folder isn't exists,will throw 
// Error: ENOENT, no such file or directory '/parent-not-exists/folda'

solution
use mkdirp,Recursively mkdir, like mkdir -p

var mkdirp = require('mkdirp');

mkdirp('/tmp/foo/bar/baz', function (err) {
    if (err) console.error(err)
    else console.log('pow!')
});
like image 144
plusmancn Avatar answered Sep 29 '22 03:09

plusmancn