4

Using node.js and Haxe, is there any way to write a function that generates a node.js modules from a Haxe file, and then returns the generated module? I'm started writing node.js modules using Haxe, and I need a way to import the modules more easily.

function requireHaxe(variableToRequire, haxeFileLocation){
    //generate a JavaScript module from the Haxe file, and then return the generated JavaScript module
}
Anderson Green
  • 30,230
  • 67
  • 195
  • 328
  • This problem shouldn't be too difficult to solve - I just need to find a way to run the Haxe compiler from node.js, get the name of the generated JavaScript file, and then import the generated JavaScript file. – Anderson Green Jan 02 '13 at 02:33
  • 1
    It's possible to generate node.js modules using Haxe, as described here: https://groups.google.com/forum/#!topic/haxelang/6lzIeg6RUC4 – Anderson Green Jan 02 '13 at 02:35
  • In node.js, it's also possible to execute a system command synchronously. http://stackoverflow.com/questions/4443597/node-js-execute-system-command-synchronously – Anderson Green Jan 02 '13 at 02:36
  • ...and here's the .hxml file that I'll need to compile haxe to node.js. https://github.com/fukaoi/HaxeNode/blob/master/compile.hxml – Anderson Green Jan 02 '13 at 02:40

1 Answers1

6

Consider this

//Haxenode.hx

class Haxenode {
  @:expose("hello")
  public static function hello(){
    return "hello";
  }
}

@:expose("hello") part is to put something in module.exports.

Now launch

haxe -js haxenode.js -dce no Haxenode

Now you can use haxenode.js in nodejs

var haxenode = require('./haxenode.js');
var hello = haxenode.hello;

So, this combined together is an answer to your question:

var cp = require('child_process');

function requireHaxe(haxeClassPath,cb){
    //generate a JavaScript module from the Haxe file, and then return the generated JavaScript module

    cp.exec('haxe -js haxenode.js -dce no ' + haxeClassPath,function(err){
        if (err){
            cb(err); return;
        }

        cb(null,require('./haxenode.js'));
    });
}

Mind that output filename is a stub.

But don't do that - better to compile haxe as build step (with all necessary compile options) and then use regular require at runtime.

Mikhail Cheshkov
  • 226
  • 2
  • 14