为什么Node.js脚本不会退出

时间:2016-05-11 08:14:40

标签: javascript node.js promise

我编写了代码来从HTTP服务获取数据并将其保存在MongoDB中 现在我直接从控制台node script.js

测试它

脚本完成它的工作,但它不会退出。我必须用CTRL + C来阻止它

为什么不自动退出?代码中的哪个位置最适合process.exit(0)(如果需要)?

/*global Promise, getData, httpReq, searchData, getHotData, storeData*/

var http = require('http');
var CoubVideo = require('./models/coubdb.js');

function CoubApi (url, numPerPage, numOfPages) {
  this.url = url;
  this.numOfPages = numOfPages;
  this.numPerPage = numPerPage;
  this.getData = getData;
  this.httpReq = httpReq;
  this.searchData = searchData;
  this.getHotData = getHotData;
  this.storeData = storeData;
}

// Get data from server
function httpReq (url) {
  var promise = new Promise (function (resolve, reject) {

    http.get(url, function (res) {
      var data = '';

      res.on('data', function (chunk) {
        data += chunk;
      });

      res.on('end', function () {
        if(data.length > 0) {
          resolve(JSON.parse(data));
        } else {
          reject("Error: HTTP request rejected!");
        }
      });

    }).on('error', function (err) {
      console.log(err);
    });

  });

  return promise;
}

// Store data in MongoDB
function storeData (data, per_page) {

  function insertVideoDoc (i) {
    CoubVideo.count({id: data.coubs[i].id}, function (err, count) {
      if (err) {
        console.log(err);
      }

      if (count === 0 || count === null) {
        var video = new CoubVideo(data.coubs[i]);

        video.save(function (err) {
          if (err) {
            console.log(err);
          }
          console.log("Saved successfully!");
        });
      } else { 
        console.log("Duplicate");
      }
    });
  }

  var i;
  for(i = 0; i < per_page; i++) {
    insertVideoDoc(i);
  }
}

// Search for coubs
function searchData (searchtext, order, page, per_page) {
  var url = this.url +
            "search?q=" + searchtext +
            "&order_by=" + order +
            "&per_page=" + per_page + 
            "&page=" + page;

  this.httpReq(url).then(function (data) {
    this.storeData(data, per_page);
  }.bind(this));
}

// Get hot coubs
function getHotData (order, page, per_page) {
  var url = this.url +
            "timeline/hot?page=" + page +
            "&per_page=" + per_page + 
            "&order_by=" + order;

  this.httpReq(url).then(function (data) {
    this.storeData(data, per_page);
  }.bind(this));
}

// Get data
function getData () { 
  var i;
  for(i = 0; i < this.numOfPages; i++) {
    this.getHotData("newest_popular", i, this.numPerPage);
  }
}

var coub = new CoubApi("http://coub.com/api/v2/", 2, 50);
coub.getData();

0 个答案:

没有答案