Child_process.exec() - How to deal with errors?


#1

So I’ve created an init script found here.

The script itself allows for compilation and execution of JXA code.

One of the current issues I am currently experiencing is when my JXA script has a syntax error, atom will just hang eternally when trying to compile the file… (Line 126)

I was wondering how to fix this issue? How do you deal with command line errors when using require(‘child_process’).exec?


#2

I’ve fixed the code now:

atom.commands.add('atom-text-editor', 'jxa:execute', function(){
    var fs = require('fs');
    var path = require('path');

    //Get the active editor and it's filepath:
    //var editor = oAtom.workspace.getActiveTextEditor();
    var editor = atom.workspace.getActiveTextEditor();

    //Build project into file
    var builtFile = build(editor)
    var compiFile = path.dirname(builtFile) + '/' + path.basename(builtFile,path.extname(builtFile)) + '.scpt'

    var alreadyCompiled = fs.existsSync(compiFile)
    //Delete compiled file, if exists
    if(alreadyCompiled){
        fs.unlinkSync(compiFile);
    }

    //Run command:
    //osacompile -l JavaScript -o newFilepath newFilepath
    //To compile to app use .App as newFilepath extension
    var exec = require('child_process').exec;
    var cmd = 'osacompile -l JavaScript -o ' + compiFile + ' ' + builtFile;
    exec(cmd, function(error, stdout, stderr) {
        // command output is in stdout
        if(error !== null){
            atom.notifications.addFatalError(stderr);
        } else {
            //Run command:
            //osacompile -l JavaScript -o newFilepath newFilepath
            //To compile to app use .App as newFilepath extension
            var exec = require('child_process').exec;
            var cmd = 'osascript ' + compiFile
            var child = exec(cmd, function(error, stdout, stderr) {
                if(error !== null){
                    atom.notifications.addFatalError(stderr)
                } else {
                    if(!alreadyCompiled){
                        fs.unlinkSync(compiFile);
                    }

                    // Delete builtFile
                    fs.unlinkSync(builtFile);
                }
            });
        }
    });

});

It looks much more chaotic to me, but relying on callbacks works much better than relying on order of commands!