aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/ChildProcess.purs
blob: ad4e20faa0a864211a6d3d6b01425caf172580ba (plain) (blame)
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
module PursLoader.ChildProcess
  ( ChildProcess()
  , spawn
  ) where

import Control.Monad.Aff (Aff(), makeAff)
import Control.Monad.Eff (Eff())
import Control.Monad.Eff.Exception (Error())

import Data.Function

foreign import data ChildProcess :: !

spawn :: forall eff. String -> [String] -> Aff (cp :: ChildProcess | eff) String
spawn command args = makeAff $ runFn4 spawnFn command args

foreign import spawnFn """
function spawnFn(command, args, errback, callback) {
  return function(){
    var child_process = require('child_process');

    var process = child_process.spawn(command, args);

    var stdout = new Buffer(0);

    var stderr = new Buffer(0);

    process.stdout.on('data', function(data){
      stdout = Buffer.concat([stdout, new Buffer(data)]);
    });

    process.stderr.on('data', function(data){
      stderr = Buffer.concat([stderr, new Buffer(data)]);
    });

    process.on('close', function(code){
      var output = stdout.toString();

      var error = output.length === 0 ? stderr.toString() : output + "\n" + stderr.toString();

      if (code !== 0) errback(new Error(error))();
      else callback(output)();
    });
  };
}
""" :: forall eff. Fn4 String
                       [String]
                       (Error -> Eff (cp :: ChildProcess | eff) Unit)
                       (String -> Eff (cp :: ChildProcess | eff) Unit)
                       (Eff (cp :: ChildProcess | eff) Unit)