例
次の Node.js スクリプトを Ruby から実行したい。
hoge.js
const json = process.argv[2];
console.log(json);
const obj = JSON.parse(json);
console.log(obj);
なお Ruby で任意のコマンドを実行する方法は複数あるが、今回は Open3.capture2 を使用する。
方法
コマンドライン引数に JSON 文字列をそのまま渡すと、Node.js 側で正しくパースできない。
require 'json'
require 'open3'
json = { name: '鹿目まどか', age: 14 }.to_json
#=> "{\"name\":\"鹿目まどか\",\"age\":14}"
stdout, _status = Open3.capture2("node hoge.js #{json}")
# SyntaxError: Unexpected token a in JSON at position 1
puts(stdout)
# name:鹿目まどか
そこで JSON 文字列を String#shellescape あるいは Shellwords.#shellescape でエスケープすると、正しく渡すことができる。
require 'json'
require 'open3'
require 'shellwords'
json = { name: '鹿目まどか', age: 14 }.to_json
#=> "{\"name\":\"鹿目まどか\",\"age\":14}"
json.shellescape
#=> "\\{\\\"name\\\":\\\"\\鹿\\目\\ま\\ど\\か\\\",\\\"age\\\":14\\}"
stdout, _status = Open3.capture2("node hoge.js #{json.shellescape}")
puts(stdout)
# {"name":"鹿目まどか","age":14}
# { name: '鹿目まどか', age: 14 }