Is it possible to use the fs API to create a directory and all  necessary subdirectories like the -p parameter does when using the mkdir command?
            Asked
            
        
        
            Active
            
        
            Viewed 6,705 times
        
    17
            
            
         
    
    
        Boris Verkhovskiy
        
- 14,854
- 11
- 100
- 103
 
    
    
        Pablo
        
- 456
- 2
- 7
- 18
- 
                    This is an answer which I wrote to another similar question https://stackoverflow.com/a/44410793/2834139 – Arvin Jun 07 '17 at 11:20
- 
                    Possible duplicate of [How to create full path with node's fs.mkdirSync?](https://stackoverflow.com/questions/31645738/how-to-create-full-path-with-nodes-fs-mkdirsync) – acdcjunior Jun 24 '19 at 03:46
3 Answers
51
            
            
        Use fs.mkdirSync with the recursive: true option:
fs.mkdirSync('/tmp/a/apple', { recursive: true });
 
    
    
        Boris Verkhovskiy
        
- 14,854
- 11
- 100
- 103
 
    
    
        Dániel Mari
        
- 519
- 4
- 2
- 
                    2Note that this API is available since v10.12.0. This answer is cleaner than the accepted answer because it does not require installing dependencies. – cadesalaberry Feb 21 '21 at 18:19
- 
                    Beware, I just wasted hours with weird issues where the node process froze so badly I could not kill it nor restart WSL, and had to reboot. This is NOT safe! – Killroy Oct 06 '22 at 08:59
- 
                    @Killroy Sounds like you have a really weird setup, because it's been part of Node for years now. Maybe file a bug with the Node folks instead? But it's almost certainly something else interfering. – Mike 'Pomax' Kamermans Feb 21 '23 at 18:06
2
            - 
                    2Note that ever since Node added `recursive: true` to the built-in `mkdir` function, this answer is no longer the right answer. – Mike 'Pomax' Kamermans Feb 21 '23 at 18:04
1
            
            
        You can also use a NPM package called fs-extra that conveniently allows you to do this:
const fs = require("fs-extra");
async function createFolder(folder) {
  try {
    await fs.ensureDirSync(folder); // guarantees the directory is created, or error.
  } catch (err) {
    throw new Error('You do not have the right permissions to make this folder.');
  }
}
 
    
    
        Bilawal Hameed
        
- 258
- 4
- 11
- 
                    1There is no reason to import fs-extra if you just need mkdirp. Node's own `mkdir` has had this functionality built in for years (and definitely at the time of this answer) in the form of the `recursive` option. – Mike 'Pomax' Kamermans Feb 21 '23 at 18:05
