-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
58 lines (44 loc) · 1.46 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
var fs = require('fs');
var path = require('path');
var Readable = require('stream').Readable;
var isStream = require('isstream');
var base64 = require('base64-stream');
module.exports = function (filePathOrStream, callback) {
if (!callback) {
throw new Error('callback is required');
}
var metadata = {};
var outputStream = process.stdout;
var inputStream;
if (typeof filePathOrStream === 'string') {
var stat = fs.statSync(filePathOrStream);
inputStream = fs.createReadStream(filePathOrStream);
metadata.size = stat.size;
metadata.name = new Buffer(path.basename(filePathOrStream)).toString('base64');
} else if (isStream(filePathOrStream)) {
inputStream = filePathOrStream;
} else {
throw new Error('Invalid parameter: it should be either string or stream');
}
// TODO Parametrize me
metadata.inline = 1;
outputStream.write('\033]1337;');
var s = 'File=';
Object.keys(metadata).forEach(function (key) {
var value = metadata[key];
s += key + '=' + value + ';';
});
s = s.slice(0, -1) + ':';
outputStream.write(s);
var base64EncodingStream = inputStream.pipe(base64.encode());
base64EncodingStream.pipe(outputStream);
base64EncodingStream.once('error', function (err) {
base64EncodingStream.removeAllListeners('end');
callback(err);
});
base64EncodingStream.once('end', function () {
base64EncodingStream.removeAllListeners('error');
outputStream.write('\07\n');
callback();
});
};