目前我正在尝试在 Hash
中获得一些东西。来自 JS 的 Ruby 格式。
我有一个看起来像这样的 JS 模块
module.exports = {
key1: "val",
key2: {
key3: "val3"
}
...
}
这只是一个字符串给我。我知道 ExecJS 在这里可能会有所帮助,但我不确定将其转换为 Hash 的最佳方法是什么。我目前正在尝试做这样的事情
contents.prepend("var module = {exports: {}};\n")
context = ExecJS.compile contents
context.eval('module.exports').to_hash
但是当给它一个像上面这样的字符串时,我从 JSON gem 中得到一个解析错误。
最佳答案
我只是尝试将其放入脚本并运行它:
require 'execjs'
str = <<-JS
// Note, you could just do `var module = {}` here
var module = {exports: {}};
module.exports = {
key1: "val",
key2: {
key3: "val3"
}
}
JS
context = ExecJS.compile str
puts context.eval('module.exports').to_hash
# => {"key1"=>"val", "key2"=>{"key3"=>"val3"}}
也许您收到 JSON 解析错误,因为该模块包含无法序列化的内容。这是另一种方法。
创建一个加载模块并将其导出为 JSON 的 JS 文件。
var fs = require('fs');
var hash = require('path/to/my_module.js');
fs.writeFileSync('path/to/output.json', JSON.stringify(hash), 'utf8');
使用 nodejs my_script.js
运行它然后从 Ruby 中读取:require 'json'
hash = JSON.parse "path/to/output.json"
关于javascript - 在 Ruby (Rails) 中评估 module.exports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67543462/