Node.js Tutorials specifically for beginners--four examples are absolutely available __JS

Source: Internet
Author: User

http://www.csdn.net/article/2013-08-28/2816731-absolute-beginners-guide-to-nodejs 
</pre><pre class= "html" name= "code" >node.js tutorials are not lacking, but most tutorials are for developers who already have a node.js base. "I have downloaded the node.js, but how can I begin?"  

"The following tutorials are specifically for node.js beginners, and will be shared through examples, step-by-step teaching you how to start a node.js journey."

What is Node.js? Many beginners don't really understand what node.js is.

The description in the nodejs.org Web site doesn't help much either. It is important to know first that node is not a Web server. It is not in itself capable of doing anything. It doesn't work like Apache. If you want it to be an HTTP server, you must write it yourself with the help of its built-in library.

Node.js is just another way of executing code on a computer, and it's a simple JavaScript Runtime. Installing Node.js Node.js is easy to install.

Just download the installer that meets your needs here.

The Node.js has been installed and what to do next. After the installation is complete, you can enter a new command "node". There are two different ways to use this "node" command.


The first, with no arguments, opens an interactive shell ">" (Repl:read-eval-print-loop), where you can execute JavaScript code.
[JS] View plaincopyprint?  
1.$ node 2.> console.log (' Hello world ');
3.Hello World 4.undefined $ node > console.log (' Hello world '); Hello World undefined in the case above, I typed "console.log" (' Hello World ') in the shell and hit enter. Node starts executing the code and displays the information just recorded, and prints out "undefined".

This is because each command returns a value, and Console.log does not have any return, so the output "undefined". Another use of the node command is to execute a JavaScript file.

This is the most common method we usually use.
hello.js [JS] View plaincopyprint? 1.<b>console.log (' Hello World '); </b&Gt
<b>console.log (' Hello World '); </b>[js] View plaincopyprint? 1.<b>$ node hello.js 2.Hello world</b> <b>$ node hello.js Hello world</b> In this case, I will "console.l OG (' Hello world '); " The command is stored in a file and is used as a parameter to the node command.

Node runs the JavaScript code in the file and prints "Hello world". Case one: File input and Output node.js contains a powerful set of libraries (modules) that can help us do a lot of things.

In the first case, I'll open a log file and parse it.
Example_log.txt [JS] View plaincopyprint? 1.<b>2013-08-09t13:50:33.166z A 2 2.2013-08-09t13:51:33.166z B 1 3.2013-08-09t13:52:33.166z C 6 4.2013-08-09T1 3:53:33.166z B 8 5.2013-08-09t13:54:33.166z b 5</b> <b>2013-08-09t13:50:33.166z A 2 2013-08-09T13:51:33.16 6Z B 1 2013-08-09t13:52:33.166z C 6 2013-08-09t13:53:33.166z b 8 2013-08-09t13:54:33.166z b 5</b> What the log data means is not important, basically To make sure that each piece of information contains a single piece of data, a letter, and a value.

I want to add up the values that follow each letter.

The first thing we have to do is read out the contents of the document.
my_parser.js [JS] View plaincopyprint?  
1.<b>//Load the FS (filesystem) module 2.var fs = require (' FS '); 3.4.//Read The contents of the file into memOry.  
5.fs.readfile (' Example_log.txt ', function (err, logdata) {6.  7.//If An error occurred, throwing it'll 8.   
Display the exception and end of our app.  
9. if (err) throw err;  10.11.   
Logdata is a Buffer and convert to string.  
var text = logdata.tostring ();

;</b> <b>//Load the FS (filesystem) module var fs = require (' FS ');
Read the contents of the file into memory. Fs.readfile (' Example_log.txt ', function (err, logdata) {//If An error occurred, throwing it'll/display the EXC
  Eption and end of our app.

  if (err) throw err;
  Logdata is a Buffer and convert to string.
var text = logdata.tostring (); ;</b> through the built-in file (FS) module, we can easily do the file input/output operation. The FS module has a ReadFile method that takes the file path, callback function as the parameter. The callback function is called after the file read is completed. The file data is read and stored in the buffer type as a basic byte array.

We can convert it to a string through the ToString () method.

Now we're going to parse it.
my_parser.js [JS] View plaincopyprint?   
1.<b>//Load the FS (filesystem) module.  
2.var fs = require (' FS '); 3.4.//Read The contents of the FILe into memory.  
5.fs.readfile (' Example_log.txt ', function (err, logdata) {6.  7.//If An error occurred, throwing it'll 8.   
Display the exception and kill our app.  
9. if (err) throw err;  10.11.   
Logdata is a Buffer and convert to string.  
var text = logdata.tostring ();  13.14.  
var results = {};  15.16.   
Break up the file into lines.  
var lines = text.split (' \ n ');  18.19.    Lines.foreach (function (line) {20.  
var parts = line.split (');  
var letter = parts[1];  
var count = parseint (parts[2]);    23.24.      if (!results[letter]) {25.  
Results[letter] = 0;  
26.} 27.  
Results[letter] + + parseint (count);  
29.});  30.31.  
Console.log (results); //{a:2, b:14, c:6} 33});
</b> <b>//Load the FS (filesystem) module.

var fs = require (' FS ');
Read the contents of the file into memory. Fs.readfile (' Example_log.txt ', function (err, logdata) {//If an error OCCURred, throwing it'll/display the exception and kill our apps.

  if (err) throw err;
  Logdata is a Buffer and convert to string.

  var text = logdata.tostring ();

  var results = {};
  Break up the file into lines.

  var lines = text.split (' \ n ');
    Lines.foreach (function (line) {var parts = line.split (');
    var letter = parts[1];

    var count = parseint (parts[2]);
    if (!results[letter]) {Results[letter] = 0;
  } Results[letter] + + = parseint (count);

  });
  Console.log (results);


{a:2, b:14, C:6}});</b> now, when you use the file as a parameter to the node command, executing the command prints out the following results and exits after execution completes.
[JS] View plaincopyprint? 1.$ node My_parser.js 2. {a:2, b:14, C:6} $ node My_parser.js {a:2, b:14, c:6} I will use Node.js as a script at large, as shown above.

It is easier to use and is a powerful substitute for scripting programs. Asynchronous callbacks as you can see in the previous example, the typical pattern for node.js is to use asynchronous callbacks. Basically, you tell node.js what to do, and it will call your function (callback function) when it's done. This is because node is single-threaded.

As you wait for the callback function to execute, node can continue to perform other transactions without being blocked until the request is completed. This is especially important for Web servers. is particularly prevalent in the process of accessing databases in modern Web applications. When you wait for the database to return results, node can process more requests. Compared to processing only one thread per connection, it enables you toA small overhead to handle thousands of parallel connections. Case two: HTTP server node is built with a module that makes it easy to create basic HTTP servers.

Take a look at the case below.
my_web_server.js [JS] View plaincopyprint?  
1.<b>var http = require (' http ');  2.3.http.createserver (function (req, res) {4.  
Res.writehead ({' Content-type ': ' Text/plain '});  
5. Res.end (' Hello world\n ');  
6.}). Listen (8080); 7.8.console.log (' Server running on port 8080 ');

</b> <b>var http = require (' http ');
  Http.createserver (function (req, res) {res.writehead ({' Content-type ': ' Text/plain '});
Res.end (' Hello world\n ');

}). Listen (8080); Console.log (' Server running on port 8080. '); </b> on top, I said yes basic HTTP server. This example does not create a full-featured HTTP server that does not handle any HTML files or pictures. In fact, whatever you ask for, it will return to "Hello World".


You run the code and enter "http://localhost:8080" in the browser, and you will see the text.
[JS] View plaincopyprint? 1.$ node My_web_server.js $ node My_web_server.js Now you may have noticed something different. Your node.js application does not exit.

This is because you create a server where your Node.js application will continue to run and respond to requests until you close it. If you want it to become a fully functional Web server, you must check the requests received, read the appropriate files, and return the requested content.

Happily, someone has already done this difficult job for you. Case THREE:Express Frame Express is a framework that makes it easy to create a Web site. You need to install it first. In addition to the node command, you also need to access the NPM command. With this tool, you can access the large set of modules created by the community.


One of them is express.
[JS] View plaincopyprint? 1.$ cd/my/app/location 2.$ npm Install Express $ cd/my/app/location $ npm Install Express when you install a module, it will appear in the directory where the application resides "n Ode_modules folder.

Now we can use express to create a basic static file server.
my_static_file_server.js [JS] View plaincopyprint?    1.<b>var Express = require (' Express '), 2.  
App = Express ();  
3.4.app.use (express.static (__dirname + '/public '));

5.6.app.listen (8080);</b> <b>var Express = require (' Express '), App = Express ();

App.use (express.static (__dirname + '/public '));
App.listen (8080);</b> [JS] View plaincopyprint? 1.$ node My_static_file_server.js $ node My_static_file_server.js Now you have created a powerful static file server. You can request access to any file you put in the public folder and display it in a browser, including HTML, pictures, and anything else. For example, put a picture named "My_image.png" in the public folder, and you can enter "Http://localhost:8080/my_image.png" in the browser to access the picture.

Of course, express also has a lot of features, you can continue to explore in the future development. NPM above we have contacted NPM, but I still want to emphasize that in the Node.js development processThe importance of the tool. It has thousands of modules to help us solve most of the typical problems encountered. 

Before reinventing the wheel, check to see if NPM has the appropriate functionality. In the previous example, we manually installed the Express. If your program contains a lot of "dependencies" (Dependency), then it is not appropriate to use this method to install them.

This npm provides a Package.json file.
Package.json [JS] View plaincopyprint?  1.<b>{2.  "Name": "Mystaticserver", 3. "Version": "0.0.1", 4. "Dependencies": {5. "Express": "3.3.x" 6. } 7.}
  </b> <b>{"name": "Mystaticserver", "Version": "0.0.1", "dependencies": {"Express": "3.3.x" The}</b> Package.json file contains basic information about the application. The "Dependencies" section describes the name and version of the module you want to install. In this case, accept any version of Express 3.3.

You can list all the dependencies you want in that section.


Instead of installing each of the dependencies before, we can now run a command to install them all.
[JS] View plaincopyprint? 1.$ NPM Install $ npm Install runs the command, and NPM looks for the "Package.json" file in the current folder.

Once found, all of the dependencies listed can be installed. The organization of the Code in most applications, your code is often split into several files. Now let's isolate the log analysis script from the first case.

This will make the program easier to test and maintain.
parser.js [JS] View plaincopyprint?   
1.<b>//Parser Constructor.  
2.var Parser = function () {3.  
4.};   
5.6.//parses the specified text. 7.parser.prototype.parse = function(text)  {8.9.  
var results = {};  10.11.   
Break up the file into lines.  
var lines = text.split (' \ n ');  13.14.    Lines.foreach (function (line) {15.  
var parts = line.split (');  
var letter = parts[1];  
var count = parseint (parts[2]);    18.19.      if (!results[letter]) {20.  
Results[letter] = 0;  
21.} 22.  
Results[letter] + + + parseint (count);  
24.});  25.26.  
return results;  
27.};   
29.//Export The Parser constructor from this module.
30.module.exports = parser;</b> <b>//Parser constructor.

var Parser = function () {};
Parses the specified text.

  Parser.prototype.parse = function (text) {var results = {};
  Break up the file into lines.

  var lines = text.split (' \ n ');
    Lines.foreach (function (line) {var parts = line.split (');
    var letter = parts[1];

    var count = parseint (parts[2]);
    if (!results[letter]) {Results[letter] = 0; } Results[letter] + = parseint (count);

  });
return results;

};
Export the Parser constructor from this module. Module.exports = parser;</b> Creates a new file here to store the log parsing script. This is just a standard JavaScript, and there are many ways to encapsulate that code.

I chose to redefine a JavaScript object, which makes it easier to unit test. The most important part of the program is "module.exports = Parser;" This line of code. It tells node what to output from the file. In this example, I output the constructor, and the user can create the instance with the parser object.

You can output anything you want.

Now let's take a look at how to import the file to use the parser object.
my_parser.js [JS] View plaincopyprint?   
1.<b>//Require my new parser.js file.  
2.var Parser = require ('./parser ');   
3.4.//Load the FS (filesystem) module.  
5.var fs = require (' FS ');   
6.7.//Read The contents of the file into memory.  
8.fs.readfile (' Example_log.txt ', function (err, logdata) {9.  A//If An error occurred, throwing it'll 11.   
Display the exception and kill our app.  
if (err) throw err;  13.14.   
Logdata is a Buffer and convert to string.  
var text = logdata.tostring ();  16.17.   
Create an instance of the Parser object. var parser = new parser (); 
19.20.   
Call the parse function.  
Console.log (Parser.parse (text)); //{a:2, b:14, c:6} 23});
</b> <b>//Require my new parser.js file.

var Parser = require ('./parser ');
Load the FS (filesystem) module.

var fs = require (' FS ');
Read the contents of the file into memory. Fs.readfile (' Example_log.txt ', function (err, logdata) {//If An error occurred, throwing it'll/display the EXC
  Eption and kill our app.

  if (err) throw err;
  Logdata is a Buffer and convert to string.

  var text = logdata.tostring ();
  Create an instance of the Parser object.

  var parser = new parser ();
  Call the parse function.
  Console.log (Parser.parse (text));

{a:2, b:14, C:6}});</b> as a module, files are introduced and you need to enter a path instead of a name. Summarize hopefully this tutorial will help you. Node.js is a powerful, flexible technology that can help solve a wide variety of problems. It's beyond our imagination.
 (Compiled: Chen revisers: Xiameng) original link: an absolute beginner ' s Guide to Node.js

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: