Nur Rony
Polyglot Programmer. Blindly love JS. An automation freak who love to cook code in React, Redux, RxJS and serve them using Docker. Married to the most beautiful girl.

Write file if parent folder dosen’t exists

Write file if parent folder dosen’t exists

Very simple and really awesome solution that I found on stackoverflow

In ES2015

import mkdirp from 'mkdirp'  
import fs from 'fs'  
import { dirname } from 'path'  
function writeFile (path, contents, cb) {  
  mkdirp(dirname(path), (err) => {
    if (err) return cb(err)
    fs.writeFile(path, contents, cb)
  })
}

In ES5

var mkdirp = require("mkdirp")  
var fs = require("fs")  
var getDirName = require("path").dirname  
function writeFile (path, contents, cb) {  
  mkdirp(getDirName(path), function (err) {
    if (err) return cb(err)
    fs.writeFile(path, contents, cb)
  })
}