06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Server-Side <strong>JavaScript</strong><br />

Consider the following example of asynchronous code execution in Node.js:<br />

var fs = require('fs');<br />

console.log('1');<br />

fs.readFile('./response.json', function (error, data) {<br />

if(!error){<br />

console.log(data);<br />

});<br />

console.log('2');<br />

In this program, we read the response.json file from the disk. When the disk I/O is<br />

finished, the callback is executed with parameters containing the argument's error, if<br />

any error occurred, and data, which is the file data. What you will see in the console<br />

is the output of console.log('1') and console.log('2') one immediately after<br />

another:<br />

Node.js does not need any additional server component as it creates its own server<br />

process. A Node application is essentially a server running on a designated port. In<br />

Node, the server and application are the same.<br />

[ 204 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!