2014-11-09 47 views
1

所以我们假设我有一个coffeescript代码的字符串,在nodejs的javascript文件中。我怎么能把这个字符串转换成javascript,而不使用终端?我试过coffeescript-compiler,但它给了我关于一个关闭套接字的错误。我在全球安装了coffeescript,并在本地安装了coffee-script编译器。如何在javascript中编译coffeescript代码的字符串?

编辑:这里是代码:

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) 
+0

你可以显示你用于'coffeescript-compiler'的代码吗?这绝对是使用的东西。 – loganfsmyth 2014-11-09 01:42:43

回答

-1

您可以使用此online converter

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

+0

不,我的意思是像我可以调用的函数来编译coffeescript,如:var code = compile('a =“foo”')',其中代码将等于var a =“foo”''。 – 2014-11-09 01:35:25

2

CoffeeScript包本身提供了编译器功能,因此对于像您这样的简单用例,它比使用coffee-compiler更容易。你可以得到你想要的东西是这样的:

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

的CoffeeScript的编译器将返回一个常规的JavaScript字符串,但随后你需要通过别的东西来要求它运行。

// 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; 
} 
相关问题