samedi 21 février 2015

Javascript error with JSHint

I brought this book: http://ift.tt/1zVomt1


And I was studying the examples and came across with this piece of code:



var http = require(‘http’);
var fs = require(‘fs’);
http.createServer(function (req, res) {
if (req.url === ‘/favicon.ico’) {
return res.end();
}
console.log(‘Incoming request to ‘ + req.url);
var i = 2;
res.writeHead(200, {‘Content-Type’: ‘text/plain’});
setTimeout(function() {
fs.readFile(__filename, {
encoding: ‘utf8’
}, function (error, contents) {
if (error) {
console.error(error);
return res.end();
}
console.log(‘sending response for ‘ + req.url);
res.end(contents);
});
}, 5000);
while(i—) {
console.log(‘Loop value: ‘ + i + ‘\r’);
}
}).listen(1337, ‘127.0.0.1’);
console.log(‘Server running at http://127.0.0.1:1337/’);


I found 3 problems:



  • The programmer uses 2 spaces, which is common among beginning programmers (it has 8 spaces now because I changed it, it should be 4, I know)

  • The code does not compile

  • Bad programming practices, like "__filename", from where he got this variable from??


So as a new javascript programmer, I may be overextending myself and getting wrong conclusions. Is this the case?


These are the errors given by JSHint(npm install):


27,12: Unexpected '—'.


28,9: Expected ')' to match '(' from line 27 and instead saw 'console'.


28,16: Expected an identifier and instead saw '.'.


28,16: Expected an assignment or function call and instead saw an expression.


28,17: Missing semicolon.


30,1: Expected ')' and instead saw '}'.


30,2: Missing semicolon.


30,2: Expected an identifier and instead saw ')'.


30,3: Expected an operator and instead saw '.'.


30,3: Expected an assignment or function call and instead saw an expression.


30,4: Missing semicolon.


So is this guy writing bad code in his book, or am I as a javascript beginning programmer overextending myself?


Aucun commentaire:

Enregistrer un commentaire