How to I run in nodejs a javascript file produced by haste?

110 Views Asked by At

If I have a file, hello.hs:

main = putStrLn "Hello, World!"

I can compile it to hello.js using haste command:

hastec hello.hs

How do I run the result hello.js file under nodejs?

2

There are 2 best solutions below

2
valderman On BEST ANSWER

By default, Haste's main is set to execute when the browser's onload event fires. This obviously makes no sense for Node, so you need to pass the --onexec flag to Haste when compiling your program:

$ hastec --onexec hello.hs

Haste uses Node to run its test suite in this way. Note, however, that with the exception of writing to standard output (like putStrLn), Haste does not map system operations (file IO, etc.) to Node equivalents. If you're writing an application that needs to interact with the OS, you're better off using vanilla GHC.

Update: Thank you, and good answer. To recap, if you want to compile and run hello.hs under node, the two lines would be:

hastec --onexec hello.hs
node hello.js
0
zumalifeguard On

haste doesn't know about node, so the .js files in produces doesn't export anything.

You need to somehow augment the .js file to export the functionality that you want, namely you need to export the hasteMain() function.

You may try the --with-js command line option to hastec

Or you may simply append the following line to the end of your hello.js file:

module.exports = hasteMain;

Once you do that, you can load hello.js as a module using require and run the code:

hasteMain = require('./hello.js');
hasteMain();

You may also want to look at ghcjs. The React team recently moved one of the modules from haste to ghcjs