UNPKG

2.47 kBJavaScriptView Raw
1/****************************************************************************
2 Copyright 2015 Apigee Corporation
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 ****************************************************************************/
16
17'use strict';
18
19var fs = require('fs');
20var _ = require('lodash');
21var util = require('util');
22
23module.exports.copyFile = function(source, target, cb) {
24 cb = _.once(cb);
25
26 var rd = fs.createReadStream(source);
27 rd.on('error', function(err) {
28 cb(err);
29 });
30
31 var wr = fs.createWriteStream(target);
32 wr.on('error', function(err) {
33 cb(err);
34 });
35 wr.on('close', function(err) {
36 cb(err);
37 });
38 rd.pipe(wr);
39};
40
41// intercepts stdout and stderr
42// returns object with methods:
43// output() : returns captured string
44// release() : must be called when done, returns captured string
45module.exports.captureOutput = function captureOutput() {
46 var old_stdout_write = process.stdout.write;
47 var old_console_error = console.error;
48
49 var captured = '';
50 var callback = function(string) {
51 captured += string;
52 };
53
54 process.stdout.write = (function(write) {
55 return function(string, encoding, fd) {
56 var args = _.toArray(arguments);
57 write.apply(process.stdout, args);
58
59 // only intercept the string
60 callback.call(callback, string);
61 };
62 }(process.stdout.write));
63
64 console.error = (function(log) {
65 return function() {
66 var args = _.toArray(arguments);
67 args.unshift('[ERROR]');
68 console.log.apply(console.log, args);
69
70 // string here encapsulates all the args
71 callback.call(callback, util.format(args));
72 };
73 }(console.error));
74
75 return {
76 output: function output(err, reply) {
77 return captured;
78 },
79 release: function done(err, reply) {
80 process.stdout.write = old_stdout_write;
81 console.error = old_console_error;
82 return captured;
83 }
84 }
85};