如何在javascript中编译coffeescript代码的string?

假设我在nodejs的javascript文件中有一串coffeescript代码。 我怎么能把这个string转换成javascript,而不使用terminal? 我试过coffeescript编译器 ,但它给了我关于一个封闭的套接字错误。 我已经安装了全局的coffeescript,并且在本地安装了coffee-script编译器。

编辑:这是代码:

var Compiler = require('coffeescript-compiler'); var cc = new Compiler(); cc.compile('a = 5', function (status, output) { if (status === 0) { // JavaScript available as a string in the `output` variable } }); 

这是它引发的错误:

 events.js:72 throw er; //unhandled 'error' event Error: This socket is closed. at Socket._write (net.js:637:19) at doWrite (_stream_writable.js:225:10) at writeOrBuffer (_stream_writable.js:215:5) at Socket.Writable.write (_stream_writable.js:182:11) at Socket.write (net.js:615:40) at doCompile (D:\TSA\App\node_modules\coffeescript-compiler\Compiler.js:33:15) at Compiler.compile (D:\TSA\App\node_modules\coffeescript-compiler\Compiler.js:46:3) at Object.<anonymous> (D:\TSA\App\coffeescript.js:4:4) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) 

CoffeeScript包本身提供了一个编译器函数,所以对于像你这样的简单用例来说,它比使用coffee-compiler更简单。 你可以用这样的东西得到你想要的东西:

 var CoffeeScript = require('coffee-script'); var compiledJS = CoffeeScript.compile('a = 5'); 

CoffeeScript编译器会返回一个常规的JavaScriptstring,但是您需要通过别的方式来运行它来需要它。

 // First the coffee-script string needs to be converted to valid javascript function requireCoffeeScript(src, filename) { var script = require("coffee-script").compile(src, {filename}); return requireJSFromString(script, filename); } // Now the valid javascript string can be 'required' and the exports returned function requireJSFromString(src, filename) { var m = new module.constructor(); m.paths = module.paths; m._compile(src, filename); return m.exports; } 

你可以使用这个在线转换器 。

或者,CoffeeScript( http://coffeescript.org/ )主页上有一个标签:“尝试CoffeeScript”,您可以在其中粘贴您的CoffeeScript代码,并在JavaScript中查看它的等效代码。