Learning Node.js

From 《Node.js 包教不包会》 – by alsotang


包管理器 npm

npm 可以自动管理包的依赖. 只需要安装你想要的包, 不必考虑这个包的依赖包.

在 PHP 中, 包管理使用的 Composer, python 中,包管理使用 easy_install 或者 pip,ruby 中我们使用 gem。而在 Node.js 中,对应就是 npm,npm 是 Node.js Package Manager 的意思。



  • Setup a project called lesson2 to fufill the function that when accessing http://localhost:3000/?q=xxxx, then get MD5 output for xxxx.
    eg. http://localhost:3000/?q=dddd


  • How to use req.query
  • Learn to use package.json to manage Node.js project

package.json 文件就是定义了项目的各种元信息,包括项目的名称,git repo 的地址,作者等等。最重要的是,其中定义了我们项目的依赖,这样这个项目在部署时,我们就不必将 node_modules 目录也上传到服务器,服务器在拿到我们的项目时,只需要执行 npm install,则 npm 会自动读取 package.json 中的依赖并安装在项目的 node_modules 下面,然后程序就可以在服务器上跑起来了。

npm init This will walk you through creating a package.json file.
Use npm install <pkg> --save afterwards to install a package and
save it as a dependency in the package.json file.
npm install express utility --save: registry is not defined, which will be installed via default settings. save is to used to record dependency into the package.json file. When installation finished, we can find out a field called “dependencies” in package.json.

How to know whether a variable is undefined?
exp 为 null 时,也会得到与 undefined 相同的结果,虽然 null 和 undefined 不一样。注意:要同时判断 undefined 和 null 时可使用本法。

var exp = undefined;
if (typeof exp == "undefined")

typeof 返回的是字符串,有六种可能:number、string、boolean、object、function、undefined。



  • When accessing http://localhost:3000, then it comes out all posts and links from CNode(https://cnodejs.org) in JSON format.
  • And output the author also.


- How to use superagent to grab a website
- How to use cheerio to analyze a website

Here we need three dependencies. They are express, superagent and cheerio.

Superagent is a library related to HTTP, which can evoke GET and POST request.
Cheerio can be treated as a jquery in Node.js version, which is used to select data from “css selector”. It’s the same as jquery.

1. make a new folder and then npm init
2. npm install express superagent cheerio --save