NodeJS:创建一个hash并返回一个函数的值



我有一个需要提取的标签列表。该列表被称为CCD_ 1。

我试图找到与列表相对应的所有"og:*"元,并且在提取的html中可用。然后,我需要用JSON向用户返回一个包含这些元标记的散列。但是process方法返回的是undefined,而不是散列。

var http = require('http');
var url = require('url');
var request = require('request');
var jsdom = require("jsdom");
var fs = require('fs');
var cssom = require('cssom');
var list = ['title', 'description']; //here the og-tags I need to extract
var meta = {};
function process(url) {
  request(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {  
      jsdom.env({
        html: body,
        scripts: [
          'http://code.jquery.com/jquery-1.5.min.js'
        ],
        done: function(errors, window) {
          var $ = window.$;
          $('meta[property^="og:"]').each(function() {
            for (var element in list) {
              if ($(this).attr('property') == 'og:' + list[element]) {
                meta[list[element]] = $(this).attr('content');
                // this works well, if I do console.log(meta), I get the hash correctly filled.
              }
            }
          });
        }
      });
    }
  });
  return meta; // this is where the probleme is. This return undefined.
}

http.createServer(function (request, response) {
  request.setEncoding('utf8');
  response.writeHead(200, {'Content-Type': 'text/plain'});
  process(url.parse(request.url, true).query['content'], function(result) {
    console.log(result); // prints no result
  });
  response.end();
}).listen(8124);
console.log('Server running at http://0.0.0.0:8124');

因为request是异步的,所以也需要使process异步。这意味着process接受一个回调参数,一旦meta可用,它就会调用该参数。现在,processlist0回调填充之前返回meta

function process(url, callback) {
  request(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {  
      jsdom.env({
        html: body,
        scripts: [
          'http://code.jquery.com/jquery-1.5.min.js'
        ],
        done: function(errors, window) {
          var $ = window.$;
          $('meta[property^="og:"]').each(function() {
            for (var element in list) {
              if ($(this).attr('property') == 'og:' + list[element]) {
                meta[list[element]] = $(this).attr('content');
                callback(null, meta);
              }
            }
          });
        }
      });
    } else {
      callback(error);
    }
  });
}

http.createServer(function (request, response) {
  request.setEncoding('utf8');
  response.writeHead(200, {'Content-Type': 'text/plain'});
  process(url.parse(request.url, true).query['content'], function(error, result) {
    console.log(result); // prints no result
  });
  response.end();
}).listen(8124);

最新更新