Node.js 如何存储axios响应以便在不同功能中使用
我有一个nodejs项目,我需要存储这个axios请求的响应数据Node.js 如何存储axios响应以便在不同功能中使用,node.js,axios,Node.js,Axios,我有一个nodejs项目,我需要存储这个axios请求的响应数据 let px2resp; async function sendPx2() { try { let data = await axios.post('https://collector-pxajdckzhd.px-cloud.net/api/v2/collector', qs.stringify(PX2data), { headers
let px2resp;
async function sendPx2() {
try {
let data = await axios.post('https://collector-pxajdckzhd.px-cloud.net/api/v2/collector', qs.stringify(PX2data), {
headers: PX2headers
});
px2resp = data;
return px2resp;
} catch (e) {
return e;
}
}
我现在的做法是
let testing = async () => {
var a = await sendPx2();
console.log(a)
}
testing();
但问题是,每当我想使用不理想的数据时,它都会发出请求。我是否可以存储此响应数据并使用它,而无需多次发出请求?您可以将数据存储在JSON文件中。。。在节点JS中使用writeFile函数:) 然后从文件中读取它以在函数中使用
fs = require('fs')
fs.readFile('helloworld.json', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
确保添加utf-8
,这样它就不会返回缓冲区数据。(假设您不想将数据存储在文件中)
这可能是您正在寻找的方法:
让px2resp;
设alreadyFetched=false;
设cachedData=null;
异步函数sendPx2(){
//检查是否已提取数据(以避免多次相同的请求)
//如果是,则返回以前提取的数据
如果(已蚀刻)返回cachedData;
//else获取数据
让数据=等待axios.post(
'https://collector-pxajdckzhd.px-cloud.net/api/v2/collector',
qs.stringify(PX2data),
{
标题:PX2headers,
}
).catch((e)=>console.log(e));//这是可选的(如果仍然需要,请使用try/catch)
//设置变量
alreadyFetched=真;
cachedData=数据;
返回数据;
}
您仍然可以正常使用现有代码,但如果以前已经获取了数据,那么这次它不会每次都获取数据
let testing=async()=>{
var a=等待sendPx2();
控制台日志(a)
}
测试();
您可以将数据存储在文件中
var fs = require("fs");
const util = require('util');
const readFile = util.promisify(fs.readFile);
const expiry = 10*60*1000 // 10 minutes
function cachedFunction(fn){
return async (...params) => {
let path = `${fn.name}:${params.join(":")}.json`
if (fs.existsSync(path)) {
let rawdata = await readFile(path, 'utf-8');
let response = JSON.parse(rawdata.toString());
console.log(response)
if(response.created_at + expiry > Date.now()){
console.log("getting from cache")
return rawdata
}
}
const data = await fn(...params)
if(data && typeof data === 'object'){
const stringifiedData = JSON.stringify({...data,created_at: Date.now()})
fs.writeFileSync(path, stringifiedData);
}
return data
}
}
async function hello(){
return {a:1,b:2}
}
async function test() {
console.log(await cachedFunction(hello)("x"))
}
test()
您可以使用一些共享服务,也可以将响应写入本地文件。稍后,您可以在测试方法中检查值或文件内容。数据是否会在任何时候过期,因此您应该重新获取以更新它?
var fs = require("fs");
const util = require('util');
const readFile = util.promisify(fs.readFile);
const expiry = 10*60*1000 // 10 minutes
function cachedFunction(fn){
return async (...params) => {
let path = `${fn.name}:${params.join(":")}.json`
if (fs.existsSync(path)) {
let rawdata = await readFile(path, 'utf-8');
let response = JSON.parse(rawdata.toString());
console.log(response)
if(response.created_at + expiry > Date.now()){
console.log("getting from cache")
return rawdata
}
}
const data = await fn(...params)
if(data && typeof data === 'object'){
const stringifiedData = JSON.stringify({...data,created_at: Date.now()})
fs.writeFileSync(path, stringifiedData);
}
return data
}
}
async function hello(){
return {a:1,b:2}
}
async function test() {
console.log(await cachedFunction(hello)("x"))
}
test()