UNPKG

2.08 kBJavaScriptView Raw
1var spawn = require('duplex-child-process').spawn;
2var fs = require('fs');
3var path = require('path');
4
5var noFileMsg = 'You need to specify filename';
6var noInputMsg = 'You need to pass text to evaluate';
7
8module.exports = function (opts) {
9 return getSpawn(opts);
10};
11
12module.exports.file = function (file, opts, cb{
13 if (typeof opts === 'function') {
14 cb = opts;
15 opts = {};
16 }
17 if(!validateInput(file, cb, noFileMsg)) return;
18
19 var stream = fs.createReadStream(file).pipe(getSpawn(opts, file));
20 if (cb) bufferStream(stream, cb);
21
22 return stream;
23};
24
25module.exports.eval = function (text, opts, cb) {
26 if (typeof opts === 'function') {
27 cb = opts;
28 opts = {};
29 }
30 if (!validateInput(text, cb, noInputMsg)) return;
31
32 var stream = getSpawn(opts);
33 if (cb) bufferStream(stream, cb);
34
35 stream.write(text);
36 stream.end();
37 return stream;
38};
39
40function validateInput (input, cb, msg) {
41 if (!input && cb === void 0) {
42 throw Error(msg);
43 }
44
45 if(!input) {
46 return cb(new Error(msg));
47 }
48
49 return true;
50}
51
52function bufferStream (stream, cb) {
53 var buffers = [], inError;
54
55 stream.on('data', function(buffer) {
56 buffers.push(buffer);
57 });
58
59 stream.on('end', function() {
60 var buffered = Buffer.concat(buffers);
61 if (inError) return;
62
63 return cb(null, buffered.toString());
64 });
65
66 stream.on('error', function(err) {
67 inError = true;
68 return cb(err);
69 });
70 return stream;
71}
72
73function getSpawn (opts, file) {
74 return spawn('osascript', argify(opts, file));
75}
76
77function argify (opts, file) {
78 var args;
79 opts = opts || {};
80 if (opts.args) {
81 args = ['-'].concat(opts.args);
82 } else {
83 args = [];
84 }
85
86 if ((file && isAppleScript(file) && !opts.type) ||
87 (opts.type && opts.type.toLowerCase() === 'applescript')) {
88 return [].concat(args);
89 }
90
91 if (opts.type) {
92 return ['-l', opts.type.toLowerCase()].concat(args);
93 }
94
95 return ['-l', 'JavaScript'].concat(args);
96}
97
98function isAppleScript (file) {
99 var ext = path.extname(file);
100 return (ext === '.scpt' || ext.toLowerCase() === '.applescript');
101}