Run JavaScript

Gramex can run JavaScript code via node.js using gramex.pynode.node.

Run JavaScript

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

JavaScript conversion

Here is how node.js() works:

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