Calling Node.js script from Rails app using ExecJS

后端 未结 4 616
遥遥无期
遥遥无期 2021-01-04 11:57

I have a Rails application that needs to run a node script. I imagine that using the ExecJS gem is the cleanest way to run JavaScript from a Rails app. However, so far, Exec

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-04 12:22

    ExecJS people say use commonjs.rb https://github.com/cowboyd/commonjs.rb

    Why can't I use CommonJS require() inside ExecJS?

    ExecJS provides a lowest common denominator interface to any JavaScript runtime. Use ExecJS when it doesn't matter which JavaScript interpreter your code runs in. If you want to access the Node API, you should check another library like commonjs.rb designed to provide a consistent interface.

    But this doesn't work basically. The require acts completely erratically - I had to execute npm -g install pdfkit fs between env = and env.require in

    require 'v8'
    require 'commonjs'
    env = CommonJS::Environment.new(V8::Context.new, path: ::Rails.root )
    env.require 'script'
    

    for the module lookup to work O.o and if I tried pointing path to the node_modules folder then it would be impossible for the gem to find script (not to mention that the #new and require are basically the only documented methods - only methods afaik - and #new is misdocumented :P)

    Your options as far as I can tell:

    1. system(node ...) - you can use Cocaine to escape some gotcha's (piping output, error handling, performance tweaks, ...) and run a cleaner syntax - this is not as bad as it looks - this is how paperclip does image postprocessing (imagemagick system package + cocaine) so I guess it's very stable and very doable
    2. expose to web api and run a separate worker on a free heroku dyno for example to do this and similar stuff you want to do with node libs
    3. use prawn :)

提交回复
热议问题