Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Build a Simple Dynamic Site with Node.js Creating a Basic Template Engine in Node.js Reading from Files

robertgruner
robertgruner
11,850 Points

How to get it done with asynchronous file loading?

So actually it is best practice to not use sync functions in Node.js. How can we achieve the putting together of the view from the different files using the "fs.readFile(file[, options], callback)" method?

Ginger Williams
Ginger Williams
6,409 Points

I was going to ask the same question. Seven months and still no solution treehouse?

James Barrett
James Barrett
13,253 Points

Andrew Chalkley Perhaps you can give some insight on this?

1 Answer

Andrew Chalkley
STAFF
Andrew Chalkley
Treehouse Guest Teacher

Hi there,

Thanks for the heads up James Barrett.

You'd have to implement some sort of queue to handle the asynchronous IO. For example, if we had a header.txt file, a content.txt file and a footer.txt file and did some code like this.

fs.readFile('header.txt', function(err, headerContent) {
   response.write(headerContent)
});


fs.readFile('content.txt', function(err, mainContent) {
   response.write(mainContent)
});

fs.readFile('footer.txt', function(err, footerContent) {
   response.write(footerContent)
});

The out put may look like...

Footer
Header
Content

Or...

Header
Footer
Content

Or any number of combinations.

You'd have to look at your template string and look for all instances of the things you want to replace and keep track of what you have done so far and then stream the string as you build it.

Using sync removes a lot of complexity in our code. I assume backend libraries like Express and Pug have a lot more complexity that would handle multiple file IO in an asynchronous fashion. This would've been a significant detour in the course. The goal was to see the general principles that would give you a sense of how frameworks and libraries work because they do all the heavy lifting and optimization for you.