I'm working on a React app where I need to initiate a file download without showing it in the browser. I've tried different approaches, but so far, the download always shows up in the browser, which is not the behavior I want. I need the download to happen silently in the background.
However, I've encountered an issue when trying to use the fs package in a React app. It seems that the fs package is not compatible with the browser environment and throws an error.
Is there any alternative approach to achieve a silent download without the file appearing in the browser window? I'd appreciate any guidance or workaround solutions to solve this issue.
Thank you in advance for your help!
Here's the code I've tried so far:
import { TOKEN, getFormattedDateYearsBack } from "./utils";
import axios from "axios";
const headers = {
Authorization: `Bearer ${TOKEN}`,
};
export async function downloadProjectIds(): Promise<void> {
const projectIds: { projectId: string }[] = [];
const url = `https://gitlab.com/api/v4/projects?archived`;
const perPage = 50;
try {
let response = await axios.get(url, {
headers,
params: {
per_page: perPage,
page: 1,
},
});
const totalPages = response.headers["x-total-pages"];
projectIds.push(
...response.data.map((project: { id: { toString: () => any } }) => ({
projectId: project.id.toString(),
}))
);
if (totalPages) {
const requests = [];
for (let page = 2; page <= totalPages; page++) {
requests.push(
axios.get(url, {
headers,
params: {
per_page: perPage,
page,
},
})
);
}
const pageResponses = await Promise.all(requests);
pageResponses.forEach((response) => {
projectIds.push(
...response.data.map((project: { id: { toString: () => any } }) => ({
projectId: project.id.toString(),
}))
);
});
}
} catch (error) {
console.error("Error while fetching project IDs:", error);
return;
}
const projectIdsJson = JSON.stringify(projectIds, null, 2);
const dataUri =
"data:application/json;charset=utf-8," +
encodeURIComponent(projectIdsJson);
const link = document.createElement("a");
link.href = dataUri;
link.download = "projectIds.json";
link.style.display = "none";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
console.log("Project IDs downloaded successfully!");
}