I am building a simple NEST api, just to learn stuff. In it there is a service which has a method called 'getTestFileAsJSON'. I am trying to build this api for a blog. There will be articles, which are files in the .txt format.
I am trying to write a method which will read said text files and return JSON as apis should, best on best practices. From what I have read depending on the size of the files ( esp. if they are huge) streams are a good idea.
I was searching around SO for resolutions or more information and finally after several threads decided on writing my method like so:
async getTestFileAsJSON() {
const text = { value: '' };
const testFileAsReadableStream = createReadStream(
join(process.cwd(), '/files/test.txt'),
);
const streamToString = async (stream) => {
const chunks = [];
for await (const chunk of stream) {
chunks.push(Buffer.from(chunk));
}
return Buffer.concat(chunks).toString('utf-8');
};
const myText = await streamToString(testFileAsReadableStream);
console.log(myText);
text.value = myText;
return JSON.stringify(text);
}
This gets the job done and I get my response. This method is async. But in my controller I do not await it. Does this mean that even thought I have used async/await nothing truly async is happening within the code and so this is why everything is working even though I am not awaiting it in the controller?:
@Get('json-file')
getStreamFile() {
return this.blogService.getTestFileAsJSON();
}