2017-02-20 50 views
0

我正在使用一些如下代码的Node.js web scraper应用程序,并试图在功能上定位我的代码。请看下图:传递一系列函数中数据的最佳方法?

const Promise = require('bluebird'); 
const fetch = require('node-fetch'); 
const cheerio = require('cheerio'); 

const scrapeUri = uri => fetch(uri); // how should i pass the uri from here 
const fetchURIs = URIs => Promise.all(URIs.map(scrapeUri)); 
const getBodies = pages => Promise.all(pages.map(page => page.text())); 
const toSource = source => cheerio.load(source); 
const shouldScrape = ($) => { 
    const shouldIndex = $('meta[name="robots"]').attr('content'); 
    if (['noindex', 'nofollow'].indexOf(shouldIndex) !== -1) { 
    return false; 
    } 
    return true; 
}; 

const objectifyContent = ($) => { // to be accessed here 
    return { 
    meta: { 
     index_timestamp: new Date(), 
     title: $('title').html(), 
     // TODO: this will totally fail in some instances, need to pass uri from initial instance 
     uri: $('link[rel="canonical"]').attr('href'), 
     description: $('meta[name="description"]').attr('content'), 
    }, 
    }; 
}; 

objectifyContent,这将是从最初的scrapeUri访问的URI,而不是试图通过访问规范获得页面的URL的途纯?我知道我可以设置一个变量并让它沿着范围继承的一些方法,但我想知道在Node.js的上下文中是否有更清晰,更实用的方法来执行此操作。

主叫方将类似于: fetchUris(myUris).then(values => getBodies(values).then(sources => res.send(sources.map(toSource).filter(shouldScrape).map(objectifyContent));)

+0

为什么不能简单地把它添加到'objectifyContent'的签名?这个签名是由某个框架决定的吗?如果没有,你不能只是使它成为'($,uri)=> {...}'或'($)=>(uri)=> {...}'? (或者是相反的顺序,这取决于你的口味,哪一个最有可能改变。) –

+0

我想问题是,这些函数被用在一系列'objectifyContent'在一系列'map'的末尾,而'filter's。我如何存储每个阵列的uri以便以后在系列中使用? – LA1CH3

+0

您必须向我们展示您使用'.map()'和'.filter()'的实际代码,以便我们在该上下文中提供最佳答案。也许你想积累的是具有多个属性的对象数组,而不是仅仅过滤一个值。他们可以为每个单位存储多个信息。 – jfriend00

回答

0

修改此scrapeUri通过承诺,通过URI,并修改相应的处理程序

const scrapeUri = uri => fetch(uri).then(
    webpage => [uri, webpage] 
) 
+0

这实际上是我用过的想法,只是我使用了'Promise.props'并使用了对象而不是数组。 – LA1CH3

相关问题