【问题标题】:How to manage a background (scraping) process with node.js如何使用 node.js 管理后台(抓取)进程
【发布时间】:2017-11-09 11:50:35
【问题描述】:

我有一个 Express 应用程序,可以从大量网站中提取数据。为此,目前我必须运行一个带有路由(例如 localhost/scrapdata)的任务,该路由获取数据并将其存储在我的 pgsql 数据库中。此任务正在无限运行。

我还有其他途径可以从我的数据库中获取数据。

用路线开始我的抓取任务是一个好策略吗?还是有其他策略?

【问题讨论】:

    标签: node.js express web-scraping background-process


    【解决方案1】:

    这不需要是一个 Express 应用程序,而是一个在指定时间间隔触发的简单 Node.js 脚本。你要找的是Cron

    如果您想保留当前的 ​​Express 应用程序,那么我建议保留其当前结构,但使用类似 node-schedule 的内容。所以在另一个文件中,你可以有类似的东西:

    // my-job.js
    const schedule = require('node-schedule')
    
    module.exports = schedule.scheduleJob('42 * * * *', () => {
      console.log('The answer to life, the universe, and everything!')
    })
    

    然后在您的主app.js 中,只需导入文件即可开始工作:

    const express = require('express')
    ...
    require('./my-job')
    

    然后在/shutdown 这样的另一条路线上,你可以这样做:

    const express = require('express')
    const j = require('./my-job')
    
    const router = express.Router()
    
    router.get('/shutdown', () => {
      j.cancel()
      res.json({ message: 'Canceled.' })
    })
    

    这只是一个想法,以上没有经过测试。

    但请记住,抓取网站是一个灰色区域。如果他们提供 API,请改用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      • 2012-03-07
      • 1970-01-01
      相关资源
      最近更新 更多