The Absolute Beginner’s Guide to Node.js( Node.js 新手指南 (Manuel Weiss))
2014-05-17 13:24
423 查看
59 inShare |
This is a republished blog post by Brandon Cannaday. Brandon is the CTO of Modulus,
a Node.js application hosting platform. Brandon organizes the Indianapolis Node.js meetup and enjoys speaking at conferences about Node’s horizontal scalability. Prior to Modulus, Brandon worked in the chemical detection and telecommunications industries.
Modulus is the first company in the industry to offer a dedicated enterprise solution called Curvature. Curvature allows you to take advantage of rapid deployments, easy scaling, and real-time analytics in the environment of your choosing, on-premises, in the
cloud, or a hybrid of the two.
There’s no shortage of Node.js tutorials out there, but most of them cover specific use cases or topics that only apply when you’ve already got Node up and running. I see comments every once and awhile that sound something like, “I’ve downloaded Node, now what?”
This tutorial answers that question and explains how to get started from the very beginning.
What is Node.js?
A lot of the confusion for newcomers to Node is misunderstanding exactly what it is. The description on nodejs.org definitelydoesn’t help.
An important thing to realize is that Node is not a webserver. By itself it doesn’t do anything. It doesn’t work like Apache. There is no config file where you point it to you HTML files. If you want it to be a HTTP server, you have to write an HTTP server
(with the help of its built-in libraries). Node.js is just another way to execute code on your computer. It is simply a JavaScript runtime.
Installing Node
Node.js is very easy to install. If you’re using Windows or Mac, installers are available on thedownload page.
I’ve Installed Node, now what?
Once installed you’ll have access to a new command called “node”. You can use the node command in two different ways. The first is with no arguments. This will open an interactive shell (REPL: read-eval-print-loop) where you can execute raw JavaScript code.In the above example I typed “console.log(‘Hello World’)” into the shell and hit enter. Node will then execute that code and we can see our logged message. It also prints “undefined” because it displays the return value of each command and console.log doesn’t
return anything.
The other way to run Node is by providing it a JavaScript file to execute. This is almost always how you’ll be using it.
hello.js
console.log('Hello World');
In this example, I moved the console.log message into a file then passed that file to the node command as an argument. Node then runs the JavaScript in that file and prints “Hello World”.
File I/O with node.js
Running plain JavaScript is fun and all, but not very useful. This is why Node.js also includes a powerful set of libraries (modules)for doing real things. In this first example I’m going to open a log file and parse it.
example_log.txt
The first thing we need to do it read the contents of the file.
my_parser.js
has a function named readFile that takes a file path and a callback. The callback will be invoked
when the file is done being read. The file data comes in the form of a Buffer, which is basically
a byte array. We can convert it to a string using the toString() function.
Now let’s add in the parsing. This is pretty much normal JavaScript so I won’t go into any details.
my_parser.js
I use Node.js a lot for scripting like this. It’s much easier and a more powerful alternative to bash scripts.
Asynchronous Callbacks in node.js
As you saw in the previous example, the typical pattern in Node.js is to use asynchronous callbacks. Basically you’re telling it to do something and when it’s done it will call your function (callback). This is because Node is single-threaded. While you’rewaiting on the callback to fire, Node can go off and do other things instead of blocking until the request is finished.
This is especially important for web servers. It’s pretty common in modern web applications to access databases. While you’re waiting for the database to return results Node can process more requests. This allows you to handle thousands of concurrent connections
with very little overhead, compared to creating a separate thread for each connection.
Create a HTTP Server with node.js
Like I said before Node doesn’t do anything out of the box. One of the built-in modules makes it pretty easy to create a basic HTTPserver, which is the example on the Node.js homepage.
my_web_server.js
your browser and you’ll see the text.
If you want this to be a full-featured web server, then you have to do that work. You have to check what was requested, read the appropriate files, and send the content back. There’s good news, though. People have already done this hard work for you.
Express for node.js
Express is a framework that makes creating most normal websites very simple. The first thing youhave to do it install it. Along with the node command you also have access to a command called “npm”. This tool gives you access to an enormous collection of modules created by the community, and one of them is Express.
my_static_file_server.js
$ node my_static_file_server.js
You now have a pretty capable static file server. Anything you put in the /public folder can now be requested by your browser and displayed. HTML, images, almost anything. So for example, if you put an image called “my_image.png” inside the public folder, you
can access it using your browser by going to http://localhost:8080/my_image.png. Of course Express
has many many more features, but you can look those up as you continue developing.
NPM
We touched on npm a little in the previous section, but I want to emphasize how important this toolwill be to normal Node.js development. There are thousands of modules available that solve almost all typical problems that you’re likely to encounter. Remember to check npm before re-inventing the wheel. It’s not unheard of for a typical Node.js application
to have dozens of dependencies.
In the previous example we manually installed Express. If you have a lot of dependencies, that’s not going to be a very good way to install them. That’s why npm makes use of a package.json file.
package.json
but this is pretty much the minimum. The dependencies section describes the name and version of the modules you’d like to install. In this case I’ll accept any version of Express 3.3. You can list as many dependencies as you want in this section.
Now instead of installing each dependency separately, we can run a single command and install all of them.
Code Organization in node.js
So far we’ve only been using a single file, which isn’t very maintainable. In most applications your code will be split into several files. There’s no standard or enforced organization to what files go where. This isn’t Rails. There’s no concept of views gohere and controllers go there. You can do whatever you want.
Let’s re-factor the log parsing script. It’s much more testable and more maintainable if we separate out the parsing logic into its own file.
parser.js
The important piece to this is the “module.exports” line. This tells Node what you’re exporting from this file. In this case I’m exporting the constructor, so users can create instances of my Parser object. You can export whatever you want.
Now let’s look at how to import this file and make use of my new Parser object.
my_parser.js
Since I exported the constructor that is what will be returned from the require statement. I can now create instances of my Parser object and use it.
Summary
Hopefully this tutorial can bridge the gap between downloading Node.js and building your first widget. Node.js isan extremely powerful and flexible technology that can solve a wide variety of problems.
I want everyone to remember that Node.js is only bound by your imagination. The core libraries are very carefully designed to provide the puzzle pieces needed to build any picture. Combine those with the modules available in npm and it’s amazing how quickly
you can begin building very complex and compelling applications.
If you have any questions or comments, feel free to drop them below.
http://blog。codeship.io/2014/05/07/nodejs-beginners-guide.html
相关文章推荐
- The Absolute Beginner’s Guide to Node.js( Node.js 新手指南 (Manuel Weiss))
- 新手教程之:循环网络和LSTM指南 (A Beginner’s Guide to Recurrent Networks and LSTMs)
- A Beginner’s Guide to npm — the Node Package Manager
- How to handle the issue of node.js msi to roll back under windows 8
- Absolute FreeBSD: The Complete Guide to FreeBSD, 2nd Edition [ILLUSTRATED]
- use noscript html tag when user disable the javascript in browser, guide user how to enable the js in different browser and retu
- The Beginner’s Guide to iptables, the Linux Firewall
- How to pass the paramater of Node.js or io.js into native C/C++ function.
- The Beginner's Guide to Using Enum Flags
- nodejs gyp WARN EACCES user "root" does not have permission to access the dev dir
- How to pass the paramater of Node.js or io.js into native C/C++ function.
- Scala新手指南中文版 -第八篇 Welcome to the Future(欢迎来到未来世界)
- Absolute Beginner's Guide to Project Management
- The Beginner’s Guide to iptables, the Linux Firewall
- A beginner's guide to GitHub (GitHub 初学者指南)
- The Beginner's Guide to Broadband and Wireless Internet
- Absolute Beginner's Guide to eBay (4th Edition)
- THE DEAD-SIMPLE STEP-BY-STEP GUIDE FOR FRONT-END DEVELOPERS TO GETTING UP AND RUNNING WITH NODE.JS,
- Absolute FreeBSD: The Complete Guide to FreeBSD, 2nd Edition [ILLUSTRATED] (Paperback) Nov.2007.eBook-BBL
- 用Python和OpenCV创建一个图片搜索引擎的完整指南 The complete guide to building an image search engine with Python and