I created the Function App, I created a Function named HttpTrigger and provided the code in the index.js file which is the following:
const { performance, promisify } = require('perf_hooks');
const fs = require('fs');
const readline = require('readline');
const multer = require('multer');
const upload = multer();
const readFileAsync = promisify(fs.readFile);
const writeFileAsync = promisify(fs.writeFile);
const processingData = [];
let sortingRequests = 0;
module.exports = async function (context, req) {
context.res = {
headers: {
'Content-Type': 'application/json'
},
};
if (req.method === 'POST') {
if (req.query.action === 'sort') {
try {
const inputFile = await processFileUpload(req);
const startTime = performance.now();
let requestsCounter = 0;
const fileContent = await readFileAsync(inputFile.path, 'utf8');
const dateArray = fileContent.split('\n');
dateArray.sort((a, b) => {
requestsCounter++;
return new Date(b) - new Date(a);
});
const sortedDateArray = dateArray.join('\n');
const data = {
requests: requestsCounter,
processingTime: performance.now() - startTime,
};
processingData.push(data);
sortingRequests += requestsCounter;
const filePath = `${context.executionContext.functionDirectory}/uploads/result.txt`;
await writeFileAsync(filePath, sortedDateArray, 'utf8');
context.res = {
status: 200,
body: { message: 'File sorted and saved as result.txt', processingData },
};
} catch (error) {
context.res = {
status: 500,
body: { error: 'Internal Server Error', details: error.message },
};
}
}
} else if (req.method === 'GET') {
if (req.query.action === 'download') {
// Handle file download
try {
const filePath = `${context.executionContext.functionDirectory}/uploads/result.txt`;
context.res = {
status: 200,
body: fs.readFileSync(filePath, 'utf8'),
headers: {
'Content-Type': 'text/plain',
'Content-Disposition': 'attachment; filename=result.txt',
},
};
context.done();
} catch (error) {
context.res = {
status: 500,
body: { error: 'Error downloading file' },
};
context.done();
}
} else if (req.query.action === 'sortingInfo') {
// Handle sorting information request
try {
const sortingInfo = {
requests: sortingRequests,
processingData: processingData,
};
context.res = {
status: 200,
body: sortingInfo,
};
context.done();
} catch (error) {
context.res = {
status: 500,
body: { error: 'Internal Server Error' },
};
context.done();
}
} else {
// Handle other GET requests as needed
try {
const greetingMessage = 'Hello from Azure Function!';
context.res = {
status: 200,
body: { message: greetingMessage },
};
context.done();
} catch (error) {
context.res = {
status: 500,
body: { error: 'Internal Server Error' },
};
context.done();
}
}
} else {
context.res = {
status: 405,
body: { error: 'Method Not Allowed' },
};
context.done();
}
};
async function processFileUpload(req) {
return new Promise((resolve, reject) => {
upload.single('inputFile')(req, {}, (err) => {
if (err) {
console.error('Error processing file upload:', err);
reject(new Error('Error processing file upload'));
} else {
resolve(req.file);
}
});
});
}
Whenever I try to send a POST or GET request to the url provided by the function I keep getting 500 (Internal Server Error).
I tried logging the error but it is always the same thing, and I can't figure out where I'm getting the code wrong because both the client-side and the server-side runs perfectly when I run it locally but it fails when I run it as a function. Does anyone have any suggestions in order to debug the code and adjust it and solve the problem?
Below is the modified code with your code to sort the dates using the Multer package in an Azure function.
Code :
Output in Postman :
json body:
Browser Output :
result.txt file is downloaded using GET method in browser as below.
Output :
It ran successfully as below,
Before sort :
After sort :