LoginSignup
21
21

More than 5 years have passed since last update.

Node.js ファイルを書き込みする際にフォルダを作成する

Last updated at Posted at 2015-06-09

ファイルを作成する際にフォルダがなかった場合、自動的に作ってほしいですよね。
そのお手軽なソリューションです。

writefile.js

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)
  })
}

writefile("c:/Users/hoge/hoge1/foga2/foo.txt","foo",function(err){
        if(err) throw err;
});

結果"c:/Users/hoge/hoge1/foga2/foo.txt"が作成されますフォルダが無ければすべて再帰的に作成されます

このとおりmkdirpを使えば簡単です。
mkdirpは

npm install mkdirp

としてインストールすればOKです。

以上。

21
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
21