Reputation: 301
So I'm trying to create an HTML file, and then just send it (as a first step in a bigger project) as a response when the user is making a GET request. Depending on what request parameters the user gives, the HTML file should have a corresponding content into it.
First, I tried a simple example and I've used an async
function since the response has to be made after the output file has been created.
Problem is: The file has the correct information in it (in this case is just a list of elements), but unfortunately, when I run the node app and I make a request, I get nothing in the body. I called res.sendFile
after the await
to make sure the file was successfully written. Am I missing something? Is my understanding about the ASYNC/AWAIT procedure wrong?
Below is a snippet of my code.
function writeFile(N, name) { //function that writes the list of elements in a html file
var stream = fs.createWriteStream(FILEPATH, 'utf-8'); //filepath being the actual output file
stream.once("open", () => {
for (let i = 0; i < N; i++) {
stream.write(`<li>idx=${i} and nm=${name}</li>\n`);
}
stream.end();
});
}
app.get('/list/:name/number/:id', (req, res) => { //the params
var fun = async() => {
try {
await writeFile(req.params.id, req.params.name); //wait for writing into file
res.sendFile(FILEPATH);
} catch (err) {
console.log(err);
res.send(err);
}
}
fun();
});
Thank you in advance :)
Upvotes: 0
Views: 249
Reputation: 2099
The function writeFile must return Promise.
function writeFile(N, name) {
return new Promise(function(resolve, reject) {
var stream = fs.createWriteStream(FILEPATH, 'utf-8'); //filepath being the actual output file
stream.once("close", resolve);
stream.once("open", () => {
for (let i = 0; i < N; i++) {
stream.write(`<li>idx=${i} and nm=${name}</li>\n`);
}
stream.end();
});
}
}
Upvotes: 1