diff --git a/bin/cmd.js b/bin/cmd.js index 5b838bb46..85005bbd1 100755 --- a/bin/cmd.js +++ b/bin/cmd.js @@ -54,16 +54,23 @@ if (b.argv.list) { var bundle = b.bundle(); bundle.on('error', errorExit); +bundle.on('end', successExit); +var tmpfile; var outfile = b.argv.o || b.argv.outfile; if (outfile) { - bundle.pipe(fs.createWriteStream(outfile)); + // we'll output to a temp file within same filesystem, then atomically overwrite outfile once successful + tmpfile = outfile + ".tmp-browserify-" + Math.random().toFixed(20).slice(2) + bundle.pipe(fs.createWriteStream(tmpfile)); } else { bundle.pipe(process.stdout); } function errorExit(err) { + if (tmpfile) fs.unlink(tmpfile, function (err) { + if (err) /* no-op, we're already exiting unhappily… */; + }); if (err.stack) { console.error(err.stack); } @@ -72,3 +79,9 @@ function errorExit(err) { } process.exit(1); } + +function successExit() { + if (tmpfile && outfile) fs.rename(tmpfile, outfile, function (err) { + if (err) errorExit(err); + }); +}