Coder Social home page Coder Social logo

node-lessons's Introduction

《Node.js 包教不包会》 -- by alsotang

注意

本书写成于 2015 年,其中的某些最佳实践或许已经发生变化。比如异步处理应更多使用 Promiseawait/async,但本书未有提及。由于 js 一直向后兼容,所以本书中的内容仍然可以正常在生产环境中使用。

为何写作此课程

在 CNode(https://cnodejs.org/) 混了那么久,解答了不少 Node.js 初学者们的问题。回头想想,那些问题所需要的思路都不难,但大部分人由于练手机会少,所以在遇到问题的时候很无措。国内唯一一本排的上号的 Node.js 书是 @朴灵(https://github.com/JacksonTian) 的 《深入浅出Node.js》(http://book.douban.com/subject/25768396/ ),但这本书离实战还是比较远的。

这个课程是希望提供更多的 Node.js 实战机会,通过每一节精心安排的课程目标,让 Node.js 的初学者们可以循序渐进地,有目的有挑战地开展 Node.js 的学习。

广告

需要内推腾讯的同学请参照此贴: https://cnodejs.org/topic/58351689bde2b59e06141e9f

更多 Node.js 入门资料请前往:https://cnodejs.org/getstart

新手搭建 Node.js 云主机,推荐使用无需备案的 DigitalOcean(https://www.digitalocean.com/)

课程列表

计划

  • 《http 中各个 header 的含义》
  • 《操作 mysql》
  • 《在全新的 vps 上搭建 node.js、mongodb、nginx》
  • 《一个简单的 blog 程序》

本课程特点

  • 每一课的课程挑战如果有能力完成,则可考虑放弃阅读课程内容
  • 对 web 开发初学者不友好,对 Windows 用户不友好,对 ruby on rails 开发者友好
  • 内容笼统,课程重点随心所欲

License

MIT

node-lessons's People

Contributors

albin3 avatar alsotang avatar bighuang624 avatar bit3725 avatar elrrrrrrr avatar fishbar avatar gruad avatar halowang avatar hashplus avatar hexhu avatar hitigerzzz avatar hugojing avatar huguangju avatar iugo avatar namelessman avatar ralph-wang avatar ricardo-li avatar zyearn avatar zzz6519003 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-lessons's Issues

Lesson4 topicUrls.forEach时写错字母了

topicUrls.forEach(function(topicUrl) {
superagent.get(topicUrl)
.end(function(err, res) {
console.log('fetch ' + topicUrl + ' successful');
ep.emit('topic_html', [topicUrl, res.Text]);
});
});
res.Text 应该是res.text

Lessons4 中挑战部分获取积分疑问

Lessons4 中挑战部分获取积分
var $ = cheerio.load(topicHtml);
var authorUrl = $('.reply_author').eq(0).attr('href');
console.log('author url: ' + authorUrl);
console.log('author: ' + $('.reply_author').eq(0).text().trim());

var score1 = '';
if(authorUrl){
var authorUrl = url.resolve(cnodeUrl, authorUrl);
superagent.get(authorUrl)
.end(function(err, res){
var $ = cheerio.load(res.text);
score1 = $('.user_profile .big').eq(0).text();
console.log(score1);
});
}
return ({
title: $('.topic_full_title').text(),
href: topicUrl,
comment1: $('.reply_content').eq(0).text().trim(),
author1: $('.reply_author').eq(0).text().trim(),
score1: score1
});
我用superagent去获取,但它是异步,导致最后返回值中score1是个空串,是否给个提示?是不是要使用同步的方式去获取这个积分?

Lesson5 callback问题

var async = require('async');

var concurrencyCount = 0;
var fetchUrl = function(url, callback) {
var delay = parseInt((Math.random() * 10000000) % 2000, 10);
concurrencyCount++;
console.log('现在的并发数是', concurrencyCount, ',正在抓取的是', url, ',耗时' + delay + '毫秒');
setTimeout(function() {
concurrencyCount--;
//callback_2 我是注释我是注释注释注释我是注释我是注释注释注释
callback(null, url + ' html content okkkkk');
}, delay);
};

var urls = [];
for (var i = 0; i < 30; i++) {
urls.push('http://datasource_' + i);
}

async.mapLimit(urls, 5, function(url, callback) {
//callback_1 我是注释我是注释注释注释我是注释我是注释注释注释我是注释我是注释注释注释
fetchUrl(url, callback);
}, function(err, result) {
console.log('final:');
console.log(result);
});

代码中我添加了两个注释 分别是callback_1和 callback_2
我看了官方的api
mapLimit(arr, limit, iterator, [callback])
iterator 接受两个参数 iterator(item, callback) 到这里我都理解
为啥在注释callback_2处调用callback就直接可以输出啊
我连函数体都没有找到 callback一直都是以参数的形式传递的
到最后直接就输出了?难道是封装了吗?我看了async的源码 也没有看太明白?
希望能解答下 谢谢.

async.mapLimit 限制问题

var superagent = require("superagent");
var async = require("async");
var cheerio = require("cheerio");

var url = require("url");

var cnodeUrl = "https://cnodejs.org/";
superagent.get(cnodeUrl)
    .end(function(err, res){
        if(err){
            // return next(err);
            console.log(err);
        }
        var $ = cheerio.load(res.text);
        var urls = [];
        $(".topic_title").each(function(index, el) {
            var that = $(el);
            var absUrl = url.resolve(cnodeUrl, that.attr("href"));
            urls.push(absUrl);
        });
        console.log("抓取地址数: "+urls.length);
        var counter = 0;
        async.mapLimit(urls, 5, function(url, callback){
            superagent.get(url)
                .end(function(err, sres){
                    var $ = cheerio.load(sres.text);
                    console.log("用户:" + $(".user_name").text() + "的积分:" + $(".big").text());
                });
        },function(err,result){
            console.log(result);
        })
    });

async.mapLimit 不是限制并发数吗? 怎么这里是限制总数的?

lesson4 eventproxy 顺序问题

获取首页的列表后,再获取详情页的信息.使用eventproxy无法保证顺序,是按获取详情页的数据后emit的顺序来的.
如果想要按首页获取到的列表顺序,是否有什么办法可以做到?

Lesson 3 里面 superagent 的使用为什么这样写?

// 用 superagent 去抓取 https://cnodejs.org/ 的内容
  superagent.get('https://cnodejs.org/')
    .end(function (err, sres) {
      // 常规的错误处理
      if (err) {
        return next(err);
      }
      // sres.text 里面存储着网页的 html 内容,

为什么 .end(function (err, sres))sres 而不是 res ?
小白一枚,看了 superagent 的文档后比较困惑,求指点,谢谢。

lesson7讲得不是很清楚

例如:开始的目标里的main.js: 类似上文提到的 fibonacci 函数。,结果后来也没有再提到main.js
例如:mocha init f2e 应该用mocha init vendor,因为例子里用的vendor文件夹
例如: 插入<script src='chai.js'></script>,这里也没讲怎么下载chai.js

抱歉新手,会有困惑。

lesson4爬虫只能爬一部分

lesson4的爬虫按照您的app.js中的代码写只能爬到部分标题:
issue
总是有一部分的标题和评论识别不出来,而且后续添加挑战部分的内容时,对应的评论者和积分也都是undefined。剩下的能识别出来的部分都是正常的。
请问是什么原因呢?如果只有我出现这种问题是与node的配置有关吗?

lesson3 npm install问题

代码如下:
u2@u2:~/lesson3$ npm install express superagent cheerio --save
npm WARN package.json [email protected] No description
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No README data
npm ERR! Linux 3.13.0-32-generic
npm ERR! argv "/home/u2/.nvm/versions/v0.12.0/bin/node" "/home/u2/.nvm/versions/v0.12.0/bin/npm" "install" "express" "superagent" "cheerio" "--save"
npm ERR! node v0.12.0
npm ERR! npm v2.5.1

npm ERR! shasum check failed for /tmp/npm-26345-15a11022/registry.npmjs.org/lodash/-/lodash-2.4.1.tgz
npm ERR! Expected: 5b7723034dda4d262e5a46fb2c58d7cc22f71420
npm ERR! Actual: 06149d1adcd371438ac0e0cc360dc03bbb46a4cd
npm ERR! From: https://registry.npmjs.org/lodash/-/lodash-2.4.1.tgz
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! http://github.com/npm/npm/issues

npm ERR! Please include the following file with any support request:
npm ERR! /home/u2/lesson3/npm-debug.log
找不到是什么问题啊,作者。

Lesson8中無法測試throw error 代碼

app.test.js

當throw初error時無法正常測試,mocha返回

  1. test/app.test.js should throw when n > 10:
    Error: Internal Server Error
    at _stream_readable.js:944:16

  2. test/app.test.js should throw when n < 0:
    Error: Internal Server Error
    at _stream_readable.js:944:16

  3. test/app.test.js should throw when n isnt Number:
    Error: Internal Server Error
    at _stream_readable.js:944:16

  4. test/app.test.js should status 500 when error:
    Error: Internal Server Error
    at _stream_readable.js:944:16

lesson7引用raw.githubusercontent.com上的chai.js在chrome中报错

https://github.com/alsotang/node-lessons/blob/master/lesson7/vendor/index.html#L11

Refused to execute script from 'https://raw.githubusercontent.com/chaijs/chai/master/chai.js' because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.
tests.js:3 Uncaught ReferenceError: chai is not defined

chrome 46.0.2490.86 (64-bit)
在firefox和safari中没有问题

通过 https://rawgit.com/ 从 GitHub 中获取正确完整的 Content-Type headers,得到开发版 https://rawgit.com/chaijs/chai/master/chai.js 和压缩版 https://cdn.rawgit.com/chaijs/chai/master/chai.js 文件路径, 并在index.html作相应替换,以解决此问题。

lesson5 async 控制并发的问题

// 并发连接数的计数器
var concurrencyCount = 0;
var fetchUrl = function (url, callback) {
// delay 的值在 2000 以内,是个随机的整数
var delay = parseInt((Math.random() * 10000000) % 2000, 10);
concurrencyCount++;
console.log('现在的并发数是', concurrencyCount, ',正在抓取的是', url, ',耗时' + delay + '毫秒');
setTimeout(function () {
concurrencyCount--;
callback(null, url + ' html content');
}, delay);
};
请问下,我在console.log处设置了断点,为什么没有马上输出内容呢?谢谢

lesson10跑了benchmark'+'变最快了

Node - 4.2.1

  • x 48,762,659 ops/sec ±1.79% (92 runs sampled)
    parseInt x 22,712,111 ops/sec ±2.80% (84 runs sampled)
    Number x 27,586,431 ops/sec ±1.15% (92 runs sampled)
    Fastest is:+

lesson4,topics.map 方法不是很理解。

你好,lesson 爬虫,写的原理明白,但是
topics = topics.map(function (topicPair) {
// 接下来都是 jquery 的用法了
var topicUrl = topicPair[0];
var topicHtml = topicPair[1];
var $ = cheerio.load(topicHtml);
return ({
title: $('.topic_full_title').text().trim(),
href: topicUrl,
comment1: $('.reply_content').eq(0).text().trim(),
});
});
这个数组的map方法是说,讲数组中的每个元素运行给定得函数,但是这个topicPair是什么意思?为什么它的0,1是topicUrl,topicHtml? 小白 不是很理解,希望可以解答下。

lesson4的并发不是太懂

Hi,刚开始学习node,对lesson4中的并发不是太明白是怎么个并发,是并发发起请求还是并发处理topics?

topicUrls.forEach(function (topicUrl) {
  superagent.get(topicUrl)
    .end(function (err, res) {
      console.log('fetch ' + topicUrl + ' successful');
      ep.emit('topic_html', [topicUrl, res.text]);
    });
});

觉得并发应该是并发去请求页面获取内容才合理,但是这里感觉是个同步的get请求呢

关于heroku部署nodejs应用报错

你好!
最近准备在heroku上部署一个nodejs应用,遇到了一个问题,
我用的是最新的express,启动项目的命令为npm start,
因此我的Procfile文件内容为:web: npm start
Deploy 到 Heroku上的过程都是正常的,但是无法启动应用,我看dashboard里的web npm start都已经是选中状态的,期待你的解答!谢谢!

English version

Are you planning on releasing an English version of this?

lesson2 无法运行

你好,
按照教程出现报错:

events.js:85
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at exports._errnoException (util.js:746:11)
at Server._listen2 (net.js:1156:14)
at listen (net.js:1182:10)
at Server.listen (net.js:1267:5)
at EventEmitter.listen (/Users/shaowei/NodeJsStudy/lesson2/node_modules/express/lib/application.js:617:24)
at Object. (/Users/shaowei/NodeJsStudy/lesson2/app.js:24:5)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)

希望有空解答一下, 多谢。

lesson6 istanbul报错

我$ mocha的时候 没有问题 但是装了istanbul后用它却出现
E:\nodejs\lesson6>istanbul cover _mocha

C:\Users\Administrator\AppData\Roaming\npm_mocha.CMD:1
(function (exports, require, module, __filename, __dirname) { @if EXIST "%~dp0
^
No coverage information was collected, exit without writing coverage information
SyntaxError: Unexpected token ILLEGAL
at Module._compile (module.js:439:25)
at Module._extensions..js (module.js:474:10)
at Object.Module._extensions..js (C:\Users\Administrator\AppData\Roaming\npm\node_modules\istanbul\lib\hook.js:102:13)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at runFn (C:\Users\Administrator\AppData\Roaming\npm\node_modules\istanbul\lib\command\common\run-with-cover.js:114:16)
at C:\Users\Administrator\AppData\Roaming\npm\node_modules\istanbul\lib\command\common\run-with-cover.js:232:17
at C:\Users\Administrator\AppData\Roaming\npm\node_modules\istanbul\lib\util\file-matcher.js:56:16
at C:\Users\Administrator\AppData\Roaming\npm\node_modules\istanbul\lib\util\file-matcher.js:35:9

新建了一个文件夹 coverage ,但是不知道为什么报了错

lesson7 测试反馈运行报错

执行 mocha-phantomjs index.html --ssl-protocol=any --ignore-ssl-errors=true后提示

An error occurred trying to launch phantomjs at "/usr/local/bin/phantomjs": Error: spawn /usr/local/bin/phantomjs ENOENT You can specify an explicit path to phantomjs via the-poption.

lesson4 title comment1 为空

有部分title coment1 为空,是否与cheerio.load()这个方法有关

topics=topics.map(function(pair){

                    var topicUrl=pair[0];
                    var topicHtml=pair[1];
                    var $=cheerio.load(topicHtml);

                    return ({
                        title:$('.topic_full_title').text().trim(),
                        href:topicUrl,
                        comment1:$('.reply_content').eq(0).text().trim()
                    });
                })

eventproxy 控制并发的疑问

var ep = new eventproxy();
ep.all('data1_event', 'data2_event', 'data3_event', function (data1, data2, data3) {
  var html = fuck(data1, data2, data3);
  render(html);
});

$.get('http://data1_source', function (data) {
  ep.emit('data1_event', data);
  });

$.get('http://data2_source', function (data) {
  ep.emit('data2_event', data);
  });

$.get('http://data3_source', function (data) {
  ep.emit('data3_event', data);
  });

如果这三组数据的获取有依赖,我们如何解耦异步?

例如:

fs.readdir('md/fs', function (err, all){
    if (err) throw err;
    var num = 0 ;
    all.forEach(function(i){
        fs.readFile('md/fs/'+i, function (err, data){
            if(err) throw err;
            num ++;
            if(num === all.length){
                // .....data....
            }
        }
    }
}

lessons6 你们都跑通过了?

$ istanbul cover _mocha

image

好像是 _mocha 里面的语法问题。

特意关注了下 mocha 和 istanbul 的版本,完全是运行 lessons 6 的代码。

希望能够多多讲讲async库的用法

在nodejs中有很多异步回调,一不小心就会调入异步的坑,尤其是异步中再循环再异步再循环这种形式~
async的github官方虽然说得比较清楚了..但是对我这种英文有点黑的小白来说看着有点压力了.
另外async配合mongoose来查询貌似比较方便
所以~顺便写写mongoose教程吧!万分感谢!

提示没有版本

输入nvm install 0.10
显示Version '0.10' not found - try nvm ls-remote to browse available versions.
输入nvm ls-remote
显示N/A

lesson7

我们首先搭建一个测试原型,用 mocha 自带的脚手架可以自动生成。

cd vendor # 进入我们的项目文件夹
npm i -g mocha # 安装全局的 mocha 命令行工具
mocha init . # 生成脚手架

应该是在lesson7文件夹下执行
mocha init vendor

lesson 3里面的抓取作者只能抓取一部分。

除了抓取title和href属性后抓取author时只能抓取一部分的author.
没整明白是什么原因。


app.get("/",function(req,res,next){
    superagent.get("https://cnodejs.org/")
        .end(function(err,sres){
            //常规的错误请求
            if(err){
                console.log(err.message);
                return res.redirect("/");
            }
            var $=cheerio.load(sres.text);
            var item=[];
            $("#topic_list .topic_title").each(function(idx,element){
                var $element=$(element);
                var href=$element.attr("href");

                item.push({
                        title:$element.attr("title"),   
                        href:$element.attr("href")                                  
                    });
                superagent.get("https://cnodejs.org"+href).end(function(err,ssres){
                    var $$=cheerio.load(ssres.text);
                    item[idx].author=$$("div.changes").find("span:nth-child(2) a").text();
                    console.log(item[idx]);  //这里打印出来的所有数据,一部分有author,一部分没有
                })
            })
            res.send(item);
        })
});

express 版本问题

在第一章里,我使用下面这条命令安装后,express-generator 会默认生成4.9.0的express版本,而不会生成4.10.2的版本,请问如何默认生成4.10.2的版本?是不是还要手动修改package.json里面的包依赖,把4.9.0改成4.10.2?

$ npm install -g express-generator

我的系统是ubuntu14.04,npm 版本2.1.9(不知道是不是系统和npm版本问题)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.