Reputation: 3271
I have file hosted on S3 bucket from where I am fetching the Excel file using an Axios request. After that I am writing that Excel file in the local filesystem. After that I am converting that Excel file data into JSON and sending it as a response; for that I am using XLSX library.
After sending the Excel file data as a JSON response I want to delete that Excel file from local filesystem.
When I am trying to delete the file it's failing to delete as well as failed to read the file. But when file is already available then it's reading the file and sending the response also.
Below is my code:
const response = await axios.get(data.me_url, { responseType: 'arraybuffer' });
if (response) {
const ostream = await fs.createWriteStream(`./${filename}`, 'binary');
ostream.write(response.data);
ostream.end();
const file = xlsx.readFile(`./${filename}`);
const sheetNames = file.SheetNames;
const totalSheets = sheetNames.length;
let parsedData = [];
for (let i = 0; i < totalSheets; i++) {
const tempData = xlsx.utils.sheet_to_json(file.Sheets[sheetNames[i]]);
tempData.shift();
parsedData.push(...tempData);
}
if (parsedData.length > 0) {
console.log('if filename',filename);
try {
fs.unlinkSync(`./${filename}`);
console.log("Delete File successfully.");
return res.status(200).send({ 'data': parsedData, 'message': 'Success', 'code': 200 });
} catch (error) {
console.log(error);
}
}
}
What am I doing wrong in the above code?
Upvotes: 0
Views: 238