UNPKG

2.24 kBJavaScriptView Raw
1'use strict';
2
3var path = require('path');
4var fs = require('fs');
5var tmpdir = require('os').tmpdir || require('os-shim').tmpdir;
6var cp = require('child_process');
7var sleep;
8var JSON = require('./json-buffer');
9try {
10 sleep = require('try-thread-sleep');
11} catch (ex) {
12 console.warn('Native thread-sleep not available.');
13 console.warn('This will result in much slower performance.');
14 console.warn('You should re-install spawn-sync if possible.');
15 sleep = function () {};
16}
17
18var temp = path.normalize(path.join(tmpdir(), 'spawn-sync'));
19
20function randomFileName(name) {
21 function randomHash(count) {
22 if (count === 1)
23 return parseInt(16*Math.random(), 10).toString(16);
24 else {
25 var hash = '';
26 for (var i=0; i<count; i++)
27 hash += randomHash(1);
28 return hash;
29 }
30 }
31
32 return temp + '_' + name + '_' + String(process.pid) + randomHash(20);
33}
34function unlink(filename) {
35 try {
36 fs.unlinkSync(filename);
37 } catch (ex) {
38 if (ex.code !== 'ENOENT') throw ex;
39 }
40}
41function tryUnlink(filename) {
42 // doesn't matter too much if we fail to delete temp files
43 try {
44 fs.unlinkSync(filename);
45 } catch(e) {}
46}
47
48function invoke(cmd) {
49 // location to keep flag for busy waiting fallback
50 var finished = randomFileName("finished");
51 unlink(finished);
52 if (process.platform === 'win32') {
53 cmd = cmd + '& echo "finished" > ' + finished;
54 } else {
55 cmd = cmd + '; echo "finished" > ' + finished;
56 }
57 cp.exec(cmd);
58
59 while (!fs.existsSync(finished)) {
60 // busy wait
61 sleep(200);
62 }
63
64 tryUnlink(finished);
65
66 return 0;
67}
68
69module.exports = spawnSyncFallback;
70function spawnSyncFallback(cmd, commandArgs, options) {
71 var args = [];
72 for (var i = 0; i < arguments.length; i++) {
73 args.push(arguments[i]);
74 }
75
76 // node.js script to run the command
77 var worker = path.normalize(__dirname + '/worker.js');
78 // location to store arguments
79 var input = randomFileName('input');
80 var output = randomFileName('output');
81 unlink(output);
82
83 fs.writeFileSync(input, JSON.stringify(args));
84 invoke('node "' + worker + '" "' + input + '" "' + output + '"');
85 var res = JSON.parse(fs.readFileSync(output, 'utf8'));
86 tryUnlink(input);tryUnlink(output);
87 return res;
88}