【问题标题】:Node.js: IMPOSSIBLE to Use Callback Result in Global Variable?Node.js:不可能在全局变量中使用回调结果?
【发布时间】:2017-02-12 11:08:42
【问题描述】:

我知道这个问题已经被问过很多次了,但是我现在已经用了 19.5 个小时来解决同样的问题而没有任何结果,我不能指望我自己能做到这一点。我在整个互联网上搜索了指南和提示,但这似乎是不可能的。我已经尝试过 Promises 和所有方法,但这不起作用。

帮助者拥有数百万个互联网。

我想做什么?

我的脚本(auto.js) 使用 Tesseract 读取图片(包含文本“A”或“B”),然后在我的脚本中使用结果文本作为一个全局变量来检查对象数组中的数字并执行其他操作(我在 node-tesseract 内无法执行此操作),但我无法执行任何操作,而是将结果记录在控制台上。如果我尝试以其他方式访问它,它不会让我这样做。

附注对于 beta 测试,我只使用 Node Command Prompt("node auto") 运行代码。

AUTO.JS:

auto.js 调用 node-tesseract 模块:

var tesseract = require('node-tesseract');

auto.js 接收 Tesseract 的结果并使用 JQuery 将其转换为数字:

    require("jsdom").env("", function(err, window) {
        var $ = require("jquery")(window);

// Char is Tesseract's result, let's convert it to numbers.

               var charNums = [
           { char: 'A', nums: '1234'}, 
           { char: 'B', nums: '5678'}
        ];

        function getNum(char)
    {
        var result = null;
        var chars = $.grep(charNums, function(e){ return e.char === char; });
                if (chars.length == 0) {
          // not found
        } else {
                result = chars[0].nums;
        }
                return result;
        }

// 2.jpg is the character's picture, let's convert it to text.

        tesseract.process('2.jpg', function(err, text) {
                var foo = "asd"; // For a test.
                foo = "bef"; // For a test.

                console.log("1: "+foo); // This works.
                console.log("2: "+text); // This works.

                foo = ""+text; // For a test.
                console.log("3: "+foo); // This works.

                foo = ""+getNum(text); //Important.
                console.log("4: "+foo); //This does not work.
        });

    });

TESSERACT.JS

'use strict';

/**
 * Module dependencies.
 */
var utils = require('./utils');
var exec = require('child_process').exec;
var fs = require('fs');
var tmpdir = require('os').tmpdir(); // let the os take care of removing zombie tmp files
var uuid = require('node-uuid');
var path = require('path');
var glob = require("glob");

var Tesseract = {

  tmpFiles: [],

  /**
   * options default options passed to Tesseract binary
   * @type {Object}
   */
  options: {
    'l': 'eng',
    'psm': 10,
    'config': null,
    'binary': 'tesseract'
  },

  /**
   * outputEncoding
   * @type {String}
   */
  outputEncoding: 'UTF-8',

  /**
   * Runs Tesseract binary with options
   *
   * @param {String} image
   * @param {Object} options to pass to Tesseract binary
   * @param {Function} callback
   */
  process: function(image, options, callback) {

    if (typeof options === 'function') {
      callback = options;
      options = null;
    }

    options = utils.merge(Tesseract.options, options);

    // generate output file name
    var output = path.resolve(tmpdir, 'node-tesseract-' + uuid.v4());

    // add the tmp file to the list
    Tesseract.tmpFiles.push(output);

    // assemble tesseract command
    var command = [options.binary, image, output];

    if (options.l !== null) {
      command.push('-l ' + options.l);
    }

    if (options.psm !== null) {
      command.push('-psm ' + options.psm);
    }

    if (options.config !== null) {
      command.push(options.config);
    }

    command = command.join(' ');

    var opts = options.env || {};

    // Run the tesseract command
    exec(command, opts, function(err) {
      if (err) {
        // Something went wrong executing the assembled command
        callback(err, null);
        return;
      }

      // Find one of the three possible extension
      glob(output + '.+(html|hocr|txt)', function(err, files){
        if (err) {
          callback(err, null);
          return;
        }
        fs.readFile(files[0], Tesseract.outputEncoding, function(err, data) {
          if (err) {
            callback(err, null);
            return;
          }

          var index = Tesseract.tmpFiles.indexOf(output);
          if (~index) Tesseract.tmpFiles.splice(index, 1);

          fs.unlink(files[0]);

            callback(null, data)
        });
      })
    }); // end exec

  }

};

function gc() {
  for (var i = Tesseract.tmpFiles.length - 1; i >= 0; i--) {
    try {
      fs.unlinkSync(Tesseract.tmpFiles[i] + '.txt');
    } catch (err) {}

    var index = Tesseract.tmpFiles.indexOf(Tesseract.tmpFiles[i]);
    if (~index) Tesseract.tmpFiles.splice(index, 1);
  };
}

var version = process.versions.node.split('.').map(function(value) {
  return parseInt(value, 10);
});

if (version[0] === 0 && (version[1] < 9 || version[1] === 9 && version[2] < 5)) {
  process.addListener('uncaughtException', function _uncaughtExceptionThrown(err) {
    gc();
    throw err;
  });
}

// clean up the tmp files
process.addListener('exit', function _exit(code) {
  gc();
});

/**
 * Module exports.
 */
module.exports.process = Tesseract.process;
    });

【问题讨论】:

  • 必须 .trim() 文本。固定的。 :)
  • 请将修复作为单独的回复发布。

标签: javascript jquery node.js callback tesseract


【解决方案1】:

更新的代码/现在工作

      var getChar = function(callback) {
            tesseract.process('2.jpg', function(err, text) {
                    var foo = "asd"; // For a test.
                    foo = "bef"; // For a test.

                    console.log("1: "+foo); // This works.
                    console.log("2: "+text); // This works and gives right result. Why only this?

                text = text.trim();
                text = text.toUpperCase();

                callback(text);
            });
      };
      var getNums = function (callback) {
    getChar(function(data){
        /* This data stack 2  */
        callback(data);
    });
};

function getNum(){
    getNums(function(data){
        var $ = require("jquery")(window);
               var charNums = [
       { char: 'A', nums: '1234'}, 
       { char: 'B', nums: '2345'}, 
       { char: 'C', nums: '3456'}, 
       { char: 'D', nums: '4567'}, 
       { char: 'E', nums: '5678'}, 
       { char: 'F', nums: '6789'}, 
       { char: 'G', nums: '7890'}, 
       { char: 'H', nums: '0987'}, 
       { char: 'J', nums: '8765'}, 
       { char: 'K', nums: '7654'}, 
       { char: 'L', nums: '6543'}, 
       { char: 'M', nums: '5432'}, 
       { char: 'N', nums: '4321'}, 
       { char: 'P', nums: '3210'}, 
       { char: 'R', nums: '2109'}, 
       { char: 'S', nums: '1098'}
    ];
                 var chars = $.grep(charNums, function(e){ return e.char === data; });
                if (chars.length == 0) {
        } else {
                var result = chars[0].nums;
        }
        console.log("Character: ", data);
        console.log("Number:", result);
// DO SOMETHING
    });
}
getNum();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-14
    • 2011-07-23
    • 2017-06-20
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多