# 需求:經網址批次上傳JSON檔 在進行某專案時,使用的雲端服務是藉由 json 檔來設定,要經過指定 URL 自行上傳。 因為檔案很多,又有頻繁更版需求,因此寫這支程式來幫助批次上傳。 程式以 Node.js 寫成。 # 專案資料夾 要上傳的 json 檔,以及要執行的程式。 ![image](https://hackmd.io/_uploads/BJ1ltruEp.png) # 先在主機上安裝 axios ``` cdn npm install axios ``` 安裝後資料夾內會像這樣: ![image](https://hackmd.io/_uploads/B18P5SOEp.png) # 主程式內容 ``` javascript // 發送 HTTP 請求的 JavaScript 函式庫 const axios = require('axios'); // Node.js 中操作電腦檔案的模組 const fs = require('fs'); // 基本 URL 與 key const baseURL = 'https://example.com/'; const key = '?key=MY_KEY'; // 不同縣市有自己的 json 檔,都用日期作為版本管理 const version = '20231011'; const cityArr = ['', '_taipei', '_taichung', '_kaohsiung']; // 設定要上傳的值 const requests = cityArr.map((city) => ({ // 上傳網址:每個要縣市的上傳網址 url: baseURL + 'myProject' + city + key, // 上傳的檔案:例如:20231011_taipei.json,並且轉成轉成 utf8 data: fs.readFileSync(version + city + '.json', 'utf8'), })); // 批次發送 put 請求 async function sendRequests() { for (const request of requests) { try { const response = await axios.put(request.url, requestData, { headers: { 'Content-Type': 'application/json' }, }); console.log(`網址:${request.url}上傳成功,查看回應:`, response.status); } catch (error) { console.error(`網址:${request.url}上傳錯誤,查看回應:`, error.message); } } } // 執行批次請求 sendRequests(); ``` # 在終端機輸入以下指令 檔案自行命名,我命名為 sendRequests.js。 ``` cdn node sendRequests.js ``` 執行後即完成批次上傳。