Node.js请求中的多个函数
node.js multiple functions within request
我试图像下面的代码一样从单个请求中抓取数据,但它不起作用。我只试了一次就成功了。如何在一个请求过程中调用多个过程?
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var link = "www.google.com";
request(link, function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
//scrape class
$('.someclass').filter(function () {
var data = $(this);
var description = data.html();
//write data to file
fs.appendFile('description.txt', description + "'n", function (err) {
if (err)
throw err;
});
});
//scrape class1
$('.someclass1').filter(function () {
var data = $(this);
var description1 = data.html();
//write data to file
fs.appendFile('description1.txt', description1 + "'n", function (err) {
if (err)
throw err;
//console.log('The "description" was appended to file!');
});
});
//scrape class2
$('.someclass2').filter(function () {
var data = $(this);
var description2 = data.html();
//write data to file
fs.appendFile('description2.txt', description2 + "'n", function (err) {
if (err)
throw err;
//console.log('The "description" was appended to file!');
});
});
}
});
Filter不是你想的那样。您正在寻找。each()。Filter接受一个列表并返回一个较小的列表。每个迭代遍历项。
function writeToFile($, methodStr, fileName, modifyFunc) {
return function () {
// Whoever calls this function gets its innerhtml written to whatever
// fileName is passed to the outer function.
var text = $(this)[methodStr]() + "'n";
if (typeof modifyfunc === 'function') {
text = modifyFunc(text);
}
fs.appendFileSync(fileName, text);
};
}
然后像这样应用
request(link, function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
// these each statements say that for every element that has .someclass
// give it the inner function in writeToFile where fileName is description.txt
$('.someclass').each(writeToFile($, 'text', 'description.txt'));
$('.someclass1').each(writeToFile($, 'html', 'description1.txt'));
$('.someclass2').each(writeToFile($, 'text', 'description.txt2', function (str){
return str + "Here is a change that will also get written to the file";
}));
}
}
相关文章:
- 为什么我的控制器没有启动函数.js脚本
- 在函数js中传递变量
- 如何在单独的文件中调用函数 js.
- 在铯中调用函数.js当事件被尝试时
- 只有setTimeout执行函数.JS
- 为什么图像选择器程序中的这个函数 js 不起作用
- 获取邮件中的信息.php从函数.js解析为manage.html
- 如何从应用程序中调用JS函数.js在Rails4视图中
- Uncatch TypeError: obj.attr 不是函数 JS
- 从 C++ 节点调用 JavaScript 函数.js扩展
- 调用 Backbone 内部的外部函数.js的视图初始化方法
- 如何使用 Scala 创建 JavaScript 函数.js
- 使用带有下划线循环的回调函数.js骨干.js项目不起作用
- 获取字段值的函数-JS
- 函数js不能递归调用自己的函数
- 在函数JS中创建带有地理代码的标记
- 循环内部的函数(js/jquery)
- 我需要帮助将此代码添加到jQuery函数.js文件中
- 未捕获类型:未定义不是函数JS错误
- 停止多个内联函数JS的事件传播