1

我想从服务对象调用 Javascript 库。

我在/app/javascript/packs/readability.js.

import Readability from '@mozilla/readability';

function articleBody(document) {
  var article = new Readability(document).parse();
  return article.content;
}

我发现 webpacker-ed 文件可以通过asset_pack_path在 Views 中使用。我尝试将其添加到我的服务对象中,如下所示(使用therubyracer gem)。

(我尝试使用ExecJS,它似乎比 therubyracer 更受欢迎,但即使使用带有 ES5 Javascript 的未处理文件,它也只会返回错误。)

cxt = V8::Context.new
cxt.load(ActionController::Base.helpers.asset_pack_path 'readability.js')
puts cxt.eval("articleBody('http://example.com/')")

这是回归No such file or directory @ rb_sysopen - /packs/js/readability-20f57636.js

localhost:3000/packs/js/readability-20f57636.js在浏览器中加载良好。

如何在服务对象中加载 webpacker 处理的文件?

4

2 回答 2

0

错误是说它找不到文件,看起来你正在保存它,/javascript但 webpacker 正在寻找js. 确保您的webpacker.yml:

default: &default
   source_path: app/javascript

代替:

default: &default
   source_path: app/js
于 2021-02-11T13:04:39.170 回答
0

如果 Javascript 未在浏览器中运行,则无需编译或转译 Javascript。您可以通过从 Ruby 执行 shell 脚本将数据从 Rails 发送到 Node 。

在服务对象(或控制器)中:

require "open3"
output, status = Open3.capture2("node ./lib/test.js", stdin_data: document)
# The `output` variable above will be returned with the content of `data` from the below script.
puts output

/lib在or中编写脚本/bin

const fs = require('fs');

fs.readFile(0, 'utf8', function(err, data) {
  if (err) throw err;
  // do your proccessing here...
  console.log(data);
});
于 2021-02-18T15:41:31.583 回答