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 Binding Values

Content.replace is not a function

So, the values never end up begin replaced when I render the page on the browser. I get an error in the replace function, which makes me believe it is not receiving the correct format of parameters (aka String). But even after attaching a toString to the end of the readFileSync method and adding the encoding utf8 parameter, it doesn't work.

const fs = require("fs");

function mergeValues(values, content) { for(let key in values) { content = content.replace("{{" + key + "}}", values[key]); } return content; }

function view(templateName, values, response) { //Read from template files var fileContents = fs.readFileSync('./views/' + templateName + ".html", {enconding: "utf8"});
fileContents = mergeValues(values, fileContents); response.write(fileContents); }

module.exports.view = view;

3 Answers

Steven Parker
Steven Parker
231,248 Points

The "Content.replace is not a function" just means that the "fileContents" argument isn't a string, which could be something that doesn't even have a "toString" method. Use a breakpoint in the dev tools, or add a console.log, to examine what is actually is before "mergeValues" gets called.

Ok so I fixed it by adding the toString() method to the parameter in the mergeValues call. Thanks for the help

Yea I figured that was the issue. I printed fileContents and it's a buffer. It seems I can't convert it to string. It has the encoding parameter and I also tried adding the toString() to fileContents. I don't know what to do now