UNPKG

2.1 kBJavaScriptView Raw
1'use strict';
2
3var path = require('path')
4 , fs = require('fs')
5 , util = require('util')
6 , logFile = path.join(__dirname, '../logs/debug.log');
7
8exports.shallowClone = function shallowClone(obj) {
9 var clone = {};
10 Object.keys(obj).forEach(function (k) {
11 clone[k] = obj[k];
12 });
13 return clone;
14};
15
16exports.pad = function pad(s, len, padding) {
17 len = len || 0;
18 padding = padding || ' ';
19
20 return len + 1 >= s.length
21 ? s + new Array(len + 1 - s.length).join(padding)
22 : s;
23};
24
25exports.log = function log(obj, depth) {
26 var s = util.inspect(obj, false, depth || 5, true);
27 fs.appendFileSync(logFile, s);
28};
29
30exports.inspect = function(obj, depth) {
31 return util.inspect(obj, false, depth || 5, true);
32};
33
34exports.existsSync = fs.existsSync || path.existsSync;
35
36/**
37 * Copies srcFile to tgtFile without checking if paths are valid and calls back when done.
38 * srcFile is streamed to tgtFile
39 *
40 * @name copyFile
41 * @function
42 * @param srcFile {String}
43 * @param tgtFile {String}
44 * @param cb {Function} called when file is completely copied or an error occurs
45 */
46exports.copyFile = function (srcFile, tgtFile, cb) {
47 var readStream = fs.createReadStream(srcFile)
48 , writeStream = fs.createWriteStream(tgtFile);
49
50 writeStream
51 .on('close', cb)
52 .on('error', cb);
53
54 readStream
55 .on('error', cb);
56
57 readStream.pipe(writeStream);
58};
59
60
61/**
62 * Copies srcFile to tgtFile without checking if paths are valid and returns when done.
63 * srcFile is copied to tgtFile in chunks
64 *
65 * @name copyFileSync
66 * @function
67 * @param srcFile {String}
68 * @param tgtFile {String}
69 * @return {void}
70 */
71exports.copyFileSync = function(srcFile, tgtFile) {
72 var buflen = 64 * 1024
73 , buf = new Buffer(buflen)
74 , fdr = fs.openSync(srcFile, 'r')
75 , fdw = fs.openSync(tgtFile, 'w')
76 , bytesRead = 1
77 , pos = 0
78 ;
79
80 while (bytesRead > 0) {
81 bytesRead = fs.readSync(fdr, buf, 0, buflen, pos);
82 fs.writeSync(fdw, buf, 0, bytesRead);
83 pos += bytesRead;
84 }
85
86 fs.closeSync(fdr);
87 return fs.closeSync(fdw);
88};