Created
January 26, 2020 19:31
-
-
Save LautaroJayat/1920bfc5a7f80bbb7b0765d23d590917 to your computer and use it in GitHub Desktop.
index.js reading the asynchronous way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const server = http.createServer((req, res) => { | |
const URL = req.url; | |
if (req.url === '/') { | |
// We try to read the method in a Synchronous way | |
// Note that we dont assign the output to a variable, | |
// instead, we store the output in the second parameter of the | |
// callback function. | |
fs.readFile('./views/index.html', (err, data) => { | |
// A little bit of error handling | |
if (err) { | |
res.writeHead(404); | |
res.write('file not found'); | |
throw err; | |
} else { | |
// We Write the headers | |
res.writeHead(200, { | |
'Content-Length': data.length, | |
'Content-Type': 'text/html', | |
}); | |
// We send the using the second argument in the callback function | |
console.log(data); | |
res.write(data); | |
res.end(); | |
} | |
}); | |
} | |
}).listen(PORT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment