Gramex can run JavaScript code via node.js
using gramex.pynode.node
.
Gramex FunctionHandlers can run JavaScript code in node.js. Here is a simple example:
from gramex.pynode import node
from tornado.gen import coroutine
@coroutine
def total(handler):
result = yield node.js('return Math.abs(x + y)', x=5, y=-10) # Run code in JS
return result
This returns the result:
{ "error": null, "result": 5 }
Run the Total example
Here is how node.js()
works:
node.js()
. Whatever
the code returns is the result. For example, node.js('return 1 + 2')
will
return 3
.node.js()
become global
variables. For example, node.js('return x + y', x=1, y=2)
returns 3
.yield node.js()
, decorate your function
with @tornado.gen.coroutine
. Also see
asynchronous functions.yield node.js()
is an object with 2
keys:result:
which contains the returned JavaScript valueerror:
which is null if there is no error, otherwise the error object
with 3 keys:name
of the errormessage
of the errorstack
has the full stack trace in JavaScriptcallback(result)
. This return the result. This is useful for async JS.Here is a practical example that uses the juice
library to convert external
CSS into inline CSS:
@coroutine
def inline_styles(handler):
code = '''
const juice = require('juice') // This is JavaScript code
return juice(html) // executed by node.js
'''
# We will take this HTML string and inline the styles
html = '''
<style>
.heading { background-color: red; }
</style>
<h1 class="heading">Heading</h1>
'''
result = yield node.js( # Call node.js
code, # Run the JavaScript code
html=html, # Pass html as a global variable
lib='juice'
)
return result['result'] # Return just the result
This returns
<h1 class="heading" style="background-color: red;">Heading</h1>
Run inline_styles