alsotang / node-lessons Goto Github PK
View Code? Open in Web Editor NEW:closed_book:《Node.js 包教不包会》 by alsotang
:closed_book:《Node.js 包教不包会》 by alsotang
不要说我矫情,我按照lz的指示操作的,结果还是一样的提示没有这个命令。
最后的解决方案:
执行 source ~/.nvm/nvm.sh
我们首先搭建一个测试原型,用 mocha 自带的脚手架可以自动生成。
cd vendor # 进入我们的项目文件夹
npm i -g mocha # 安装全局的 mocha 命令行工具
mocha init . # 生成脚手架
应该是在lesson7文件夹下执行
mocha init vendor
这些工具也算是方便开发吧,编辑后自动重启。且部署过程也很有用。
现在的做法是先把远程的clone下来,在把远程目录的.git复制到我的项目目录。在push到origin master上去,并没有heroku这个origin
看这一课发现了node_modules下的.bin文件夹,
然后搜了下node_modules .bin看到No need for globals - npm scripts add .bin to PATH,
然后搜了下npm scripts发现了segment fault下的一篇文章用npm-run自动化任务写的很不错,个人觉得简单的任务完全可以用npm-scripts替代,要比Makefile简单一些:)
我$ 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 ,但是不知道为什么报了错
除了抓取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);
})
});
比如var q = req.query.q;
这个取到undefined,如何解决这个错误?
log4js 产生大量的buffer对象,导致内存暴涨
如题。系统是Win7。
直接run macha-phantomjs f2e\index.html
运行没问题。
package.json中相应部分修改如下,无法运行,会报错。
"scripts": {
"test": "./node_modules/.bin/mocha-phantomjs f2e/index.html"
}
请问是什么问题?如何解决呢?谢谢
代码如下:
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
找不到是什么问题啊,作者。
得不到完整的sres.text
可以添加 JavaScript秘密花园
执行 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.
我的机器是win8
用浏览器打开时能看到所有内容的,但是用superagent只能抓取如题所示的一句话,尝试使用request模块去抓也是一样的结果
请问是什么原因呢,该如何解决呢?谢谢
例如:开始的目标里的main.js: 类似上文提到的 fibonacci 函数。
,结果后来也没有再提到main.js
例如:mocha init f2e
应该用mocha init vendor
,因为例子里用的vendor文件夹
例如: 插入<script src='chai.js'></script>
,这里也没讲怎么下载chai.js
抱歉新手,会有困惑。
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请求呢
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
在nodejs中有很多异步回调,一不小心就会调入异步的坑,尤其是异步中再循环再异步再循环这种形式~
async的github官方虽然说得比较清楚了..但是对我这种英文有点黑的小白来说看着有点压力了.
另外async配合mongoose来查询貌似比较方便
所以~顺便写写mongoose教程吧!万分感谢!
app.test.js
當throw初error時無法正常測試,mocha返回
test/app.test.js should throw when n > 10:
Error: Internal Server Error
at _stream_readable.js:944:16
test/app.test.js should throw when n < 0:
Error: Internal Server Error
at _stream_readable.js:944:16
test/app.test.js should throw when n isnt Number:
Error: Internal Server Error
at _stream_readable.js:944:16
test/app.test.js should status 500 when error:
Error: Internal Server Error
at _stream_readable.js:944:16
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 不是限制并发数吗? 怎么这里是限制总数的?
如 【css-select】模块
// 用 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 的文档后比较困惑,求指点,谢谢。
Are you planning on releasing an English version of this?
你好,
按照教程出现报错:
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)
希望有空解答一下, 多谢。
https://github.com/Ricardo-Li/node-practice-2
该链接失效了, 只需要app.js和Procfile两个文件吗?
将 https://github.com/Ricardo-Li/node-practice-2 这个项目部署上 heroku,成为一个线上项目
抓取的网页编码是GBK,输出乱码请问怎么解决,谢谢?
大家看完课程之后,可以把自己的实践成果上传上来(或者贴个链接)。
比如我看了课程3之后,就写了个这个玩意儿...
https://github.com/happlex/uncontrolled-spider
这样,高手无聊的时候可以给新手做些指导...
新手,也可以参考更多的程序,写出更好玩的程序!~
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的源码 也没有看太明白?
希望能解答下 谢谢.
// 并发连接数的计数器
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处设置了断点,为什么没有马上输出内容呢?谢谢
你好,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? 小白 不是很理解,希望可以解答下。
有部分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()
});
})
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....
}
}
}
}
输入nvm install 0.10
显示Version '0.10' not found - try nvm ls-remote
to browse available versions.
输入nvm ls-remote
显示N/A
获取首页的列表后,再获取详情页的信息.使用eventproxy无法保证顺序,是按获取详情页的数据后emit的顺序来的.
如果想要按首页获取到的列表顺序,是否有什么办法可以做到?
在第一章里,我使用下面这条命令安装后,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版本问题)
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是个空串,是否给个提示?是不是要使用同步的方式去获取这个积分?
Node - 4.2.1
发现很多网页都是前端渲染的。怎么爬呢
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作相应替换,以解决此问题。
你好!
最近准备在heroku上部署一个nodejs应用,遇到了一个问题,
我用的是最新的express,启动项目的命令为npm start,
因此我的Procfile文件内容为:web: npm start
Deploy 到 Heroku上的过程都是正常的,但是无法启动应用,我看dashboard里的web npm start都已经是选中状态的,期待你的解答!谢谢!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.