大量のCurlのPOSTリクエストのレスポンスをデータ出力したい時があり、Node.jsで実装したので、メモ。
var fs = require('fs');
const execSync = require('child_process').execSync;
const shellFile = 'curl.txt.';
const output = 'output.txt';
// sync
fs.readFileSync(shellFile).toString().split('\n').forEach(function (line) {
var result = execSync(line).toString(); //buffa → string
// console.log(result)
fs.appendFileSync(output, result);
});
// async
// const exec = require('child_process').exec;
// fs.readFileSync(shellFile).toString().split('\n').forEach(function (line) {
// exec(line, (err, stdout, stderr) => {
// if (err) { console.log(err); }
// console.log(stdout);
// });
// var result = stdout.toString(); //buffa → string
// fs.appendFileSync(output, result);
// });
curl.txtの中身はこんな感じ
curl -X POST https://※※※※ -H "Content-type: application/json" -d "{'question':'あ'}"
curl -X POST https://※※※※ -H "Content-type: application/json" -d "{'question':'ああ'}"
curl -X POST https://※※※※ -H "Content-type: application/json" -d "{'question':'あああ'}"
curl -X POST https://※※※※ -H "Content-type: application/json" -d "{'question':'あああ'}"
curl -X POST https://※※※※ -H "Content-type: application/json" -d "{'question':'ああああ'}"
ホントはシェルでやりたかったが、Mac初心者なので、うまくできなかったので、なれているNodeで実装した。