UNPKG

1.65 kBJavaScriptView Raw
1var fs = require('fs');
2var _ = require('lodash');
3var util = require('util');
4
5module.exports.copyFile = function(source, target, cb) {
6 cb = _.once(cb);
7
8 var rd = fs.createReadStream(source);
9 rd.on('error', function(err) {
10 cb(err);
11 });
12
13 var wr = fs.createWriteStream(target);
14 wr.on('error', function(err) {
15 cb(err);
16 });
17 wr.on('close', function(err) {
18 cb(err);
19 });
20 rd.pipe(wr);
21};
22
23// intercepts stdout and stderr
24// returns object with methods:
25// output() : returns captured string
26// release() : must be called when done, returns captured string
27module.exports.captureOutput = function captureOutput() {
28 var old_stdout_write = process.stdout.write;
29 var old_console_error = console.error;
30
31 var captured = '';
32 var callback = function(string) {
33 captured += string;
34 };
35
36 process.stdout.write = (function(write) {
37 return function(string, encoding, fd) {
38 var args = _.toArray(arguments);
39 write.apply(process.stdout, args);
40
41 // only intercept the string
42 callback.call(callback, string);
43 };
44 }(process.stdout.write));
45
46 console.error = (function(log) {
47 return function() {
48 var args = _.toArray(arguments);
49 args.unshift('[ERROR]');
50 console.log.apply(console.log, args);
51
52 // string here encapsulates all the args
53 callback.call(callback, util.format(args));
54 };
55 }(console.error));
56
57 return {
58 output: function output(err, reply) {
59 return captured;
60 },
61 release: function done(err, reply) {
62 process.stdout.write = old_stdout_write;
63 console.error = old_console_error;
64 return captured;
65 }
66 }
67};