18.05.2016 Views

Mittwoch, 18. Mai, 2016

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Delving into Node.js and Express web framework 27<br />

1 var hello = require('hello');<br />

2 hello();<br />

Node.js comes pre-bundled with some modules (like for example a file reading module fs⁶⁹, http⁷⁰<br />

module, etc.) which are documented (along with many other modules) in its documentation⁷¹, but<br />

there is also a vast number of third party modules (as of the date of this post there is a total<br />

of 105006 of them and you can check the current numbers on modulescount.com⁷²). NPM (node<br />

package manager, about which we spoke in the previous tutorial) installs these modules in a folder<br />

named node_modules under the root folder of your application and you can just require them as<br />

you would normally require a core module.<br />

Lets build a Node.js web server<br />

The code for the simples Node.js web server ever:<br />

1 var http = require('http');<br />

2 var port = 1337;<br />

3<br />

4 http.createServer(function(req, res) {<br />

5 res.writeHead(200, {<br />

6 'Content-Type': 'text/plain'<br />

7 });<br />

8<br />

9 res.end("Hello Mitnick, you've just stumbled on the simplest web server ev\<br />

10 er");<br />

11 }).listen(port);<br />

12<br />

13 console.log('Our awesome web server running at http://localhost:'+ port);<br />

If you save the previous code listing in a file named server.js and run it with node via command<br />

prompt like this (once in the root folder of your application - fancy name for where the actual<br />

server.js file is placed):<br />

1 $ node server.js<br />

then, if you open up your browser and type in http://localhost:1337⁷³, you will see the following<br />

output:<br />

⁶⁹http://nodejs.org/api/fs.html<br />

⁷⁰http://nodejs.org/api/http.html<br />

⁷¹http://nodejs.org/api/<br />

⁷²http://www.modulecounts.com/<br />

⁷³http://localhost:1337

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

Saved successfully!

Ooh no, something went wrong!