From b83fae147542cbe88b5aac590685fd6105eec5c2 Mon Sep 17 00:00:00 2001 From: Harshith Kashyap Date: Sat, 8 Oct 2016 02:57:36 +0530 Subject: [PATCH] feat: Create destination filepath using mkdirp if it does not exist before writing (#25) --- index.js | 13 ++++++++++--- package.json | 6 ++++-- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index a0bbf89..ea18beb 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,7 @@ var crypto = require('crypto'); var EventEmitter = require('events').EventEmitter; var fs = require('fs'); var path = require('path'); +var mkdirp = require('mkdirp'); var PATTERN_KEYS = Object.keys(path.parse('')).concat('hash'); @@ -81,11 +82,17 @@ module.exports = function hashmark(contents, options, callback) { mapEvents.emit('file', stream.fileName, fileName); }); } else { - fs.writeFile(fileName, contents, function (err) { + mkdirp(path.dirname(fileName), function (err) { if (err) { return mapEvents.emit('error', err); - } - mapEvents.emit('file', stream.fileName, fileName); + } else { + fs.writeFile(fileName, contents, function (err) { + if (err) { + return mapEvents.emit('error', err); + } + mapEvents.emit('file', stream.fileName, fileName); + }); + } }); } diff --git a/package.json b/package.json index b602fac..29bc111 100644 --- a/package.json +++ b/package.json @@ -29,12 +29,14 @@ "test17": "mkdir -p testdir/sub/nested && echo Test1 > testdir/sub/test.js && echo Test2 > testdir/sub/test2.js && ./bin/hashmark -d md5 -l 4 --cwd 'testdir' 'sub/*' '{dir}/{name}-{hash}{ext}' && rm testdir/sub/test.js testdir/sub/test2.js testdir/sub/test-fa02.js testdir/sub/test2-856b.js && rmdir -p testdir/sub/nested", "test18": "mkdir -p testdir/sub && echo 'Test --cwd without {dir} in pattern' > testdir/sub/test.js && echo Test2 > testdir/sub/test2.js && ./bin/hashmark -d md5 -l 4 --cwd 'testdir/sub' '*' '{name}-{hash}{ext}' && rm testdir/sub/test.js testdir/sub/test2.js testdir/sub/test-84c5.js testdir/sub/test2-856b.js && rmdir -p testdir/sub", "test19": "mkdir -p testdir/sub && echo 'Test --cwd and --asset-map' > testdir/sub/test.js && ./bin/hashmark -l 4 --cwd 'testdir/sub' --asset-map assets.json '*' '{name}-{hash}{ext}' && (grep -e '\"test\\.js\":\\s*\"test-7068.js\"' testdir/sub/assets.json || (echo '\nWrong content in asset-map file' 1>&2; exit 1)) && rm testdir/sub/assets.json && rm -rf testdir", - "test": "for i in $(seq 1 19); do rm -rf testdir; npm run test$i; done" + "test20": "echo 'Create and write file if the directory does not exist' | ./bin/hashmark 'newtestdir/newtestsubdir/test.{hash}.js' && rm -rf newtestdir", + "test": "for i in $(seq 1 20); do rm -rf testdir; npm run test$i; done" }, "author": "Keith Cirkel (http://keithcirkel.co.uk)", "license": "MIT", "dependencies": { - "cli": "^1.0.0" + "cli": "^1.0.0", + "mkdirp": "^0.5.1" }, "repository": { "type": "git",