title: How to ensure all directories exist before to fs.writeFile using node.js
body: <p>I'm wondering what is the proper way to ensure that all folder in a path exist before to write a new file.</p>
  
  <p>In the following example, the code fails because the folder <code>cache</code> doesn't exists.</p>
  
  <pre><code>    fs.writeFile(__config.path.base + '.tmp/cache/shared.cache', new Date().getTime(), function(err) {
          if (err){
              consoleDev('Unable to write the new cache timestamp in ' + __filename + ' at ' + __line, 'error');
          }else{
              consoleDev('Cache process done!');
          }
  
          callback ? callback() : '';
      });
  </code></pre>
  
  <p><strong>Solution:</strong></p>
  
  <pre><code>    // Ensure the path exists with mkdirp, if it doesn't, create all missing folders.
      mkdirp(path.resolve(__config.path.base, path.dirname(__config.cache.lastCacheTimestampFile)), function(err){
          if (err){
              consoleDev('Unable to create the directories "' + __config.path.base + '" in' + __filename + ' at ' + __line + '\n' + err.message, 'error');
          }else{
              fs.writeFile(__config.path.base + filename, new Date().getTime(), function(err) {
                  if (err){
                      consoleDev('Unable to write the new cache timestamp in ' + __filename + ' at ' + __line + '\n' + err.message, 'error');
                  }else{
                      consoleDev('Cache process done!');
                  }
  
                  callback ? callback() : '';
              });
          }
      });
  </code></pre>
  
  <p>Thanks!</p>