node.js解析bash下的curl命令并发送请求
const { promises: fs } = require("fs"); const https = require('https'); function https_request(url, headers, data) { const oUrl = new URL(url); const requestOptions = { hostname: oUrl.hostname, path: oUrl.pathname, method: 'POST', headers, rejectUnauthorized: true, secureProtocol: 'TLSv1_2_method', }; console.log(requestOptions); return new Promise((resolve, reject) => { const request = https.request(requestOptions, (response) => { const chunks = []; response.on('data', (chunk) => chunks.push(chunk)); response.on('end', () => { const responseBody = Buffer.concat(chunks).toString(); resolve(responseBody); }); }); request.on('error', (error) => reject(error)); if (requestOptions.method === 'POST') { request.write(data); } request.end(); }); } function curl_get_url(curlString) { const curlRegex = /curl\s'(.+)'/; const match = curlRegex.exec(curlString); if (match === null) { throw new Error('错误的URL地址'); } return match[1]; } function curl_get_headers(curlString) { const headers = []; const curlRegex = /\s+-H\s+'(.+)'\s+/g; while((match = curlRegex.exec(curlString)) !== null) { headers.push(match[1]); }; const headers2 = headers.reduce((obj, str) => { const sSign = ': '; const i = str.indexOf(sSign); const key = str.substr(0, i); const value = str.substr(i + sSign.length); obj[key.trim()] = value.trim(); return obj; }, {}); return headers2; } function curl_get_data(curlString) { const curlRegex = /--data-raw\s+'(.+)'\s+/; const match = curlRegex.exec(curlString); if (match === null) { throw new Error('错误的data'); } return match[1]; } function curlToNode(curlString) { const url = curl_get_url(curlString); const headers = curl_get_headers(curlString); const data = curl_get_data(curlString); return https_request(url, headers, data); } (async () => { const curlString = await fs.readFile("curl.txt", "utf-8"); const sHTML = await curlToNode(curlString); console.log(sHTML); })();
标签:node,const,js,headers,curl,curlString,data,match From: https://www.cnblogs.com/xiangxisheng/p/17227842.html