我有一個 API 會定期向 RESTAPI 發出請求并將資料存盤到我的資料庫中,現在我想為某些資料添加一個新功能:通過對我的 API 的請求下載一些資料,然后,我的 API 向RESTAPI,但我不希望這些資料存盤在我的資料庫中,我希望它以 JSON 或 CSV 格式下載。
我設法創建了請求,我將請求編碼到 RESTAPI 并設法將 JSON 放入包含所有資料的變數中,我卡在那里,如何使這些資料下載到目錄中?
我使用帶有彎曲、getJSON、mssql、https的javascript nodeJS。
函式代碼:
async function descargarDatosOpendata(anioIni, anioFin, Indicativo){
try{
while(anioIni == anioFin || anioIni < anioFin){
console.log("first");
var http = require("https");
var options = {
"method": "GET",
"hostname": "opendata.aemet.es",
"path": "/opendata/api/valores/climatologicos/mensualesanuales/datos/anioini/" anioIni "/aniofin/" anioIni "/estacion/" Indicativo "",
"headers": {
"cache-control": "no-cache",
"api_key": "MYKEY"
}
};
console.log("second");
var req = http.request(options, function (res) {
console.log("tercera");
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", async function () {
console.log("endChunk");
var body = Buffer.concat(chunks);
console.log(body);
var bodyString = body.toString();
bodyJSON = JSON.parse(bodyString);
console.log(bodyJSON);
console.log(bodyJSON.datos);
if (bodyJSON.estado == 200 && bodyJSON.descripcion == "exito") {
let obj = await getJSON(bodyJSON.datos);
console.log(obj)
}
});
});
anioIni ;
req.end();
}
}
catch (err) {
console.log(err);
}
}
obj log是json格式的資料:[{data}]
uj5u.com熱心網友回復:
如果此代碼在 Node 中運行,則應使用 Nodefs
模塊。appendFile
如果它已經存在,該方法將創建一個新檔案或附加到它。了解有關 fs 的更多資訊
示例代碼
var fs = require('fs');
fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/471237.html
標籤:javascript https 要求
上一篇:JS無法匯入npm模塊
下一篇:無法從url查詢陣列引數