Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
218,860 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