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
Heng Liu
16,220 PointsPls help me understand this code
I just start learning Node.js, and I have problem understanding the following code:
var fs = require('fs');
var http = require('http');
var url = require('url');
var mysql = require('mysql');
var db = mysql.createConnection({});
db.connect();
var template = function(vars, callback) {
fs.readFile('./base.html', { flag: 'rw' }, function(err, data) {
c = 0;
Object.keys(vars).forEach(function(k){
data.replace('{{'+k+'}}', vars[k]);
if(++c === vars.length) callback(data);
})
});
}
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var params = url.parse(req.url, true).query;
if (req.url === '/') {
fs.readFile('./index.html', function(err, data){
template({ content: data }, function(html){
res.end(html);
});
});
}
}).listen(80);
I know this code is replacing something in index.html with data in base.html, but I don't know how {content:data} works here? And why in html file there are "{{" and "}}"? And what is {flag : 'rw'}? Is this read and write authorization? I appreciate if someone can explain to me in detail.
2 Answers
Jonathan Leon
18,813 PointsFrom what I understand, this is a template engine that changes the html based on the forEach loop above, and replaces {{k}} strings in the html with vars[k].
What is this lesson?
Unsubscribed User
501 PointsWhat this code should do? Please write a short specifiaction becouse for me it's not clear. I will give you the comments afterward.
Heng Liu
16,220 PointsHeng Liu
16,220 PointsIt's not a lesson here. I saw this code from somewhere else.