首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Node.js:不可能在全局变量中使用回调结果?

Node.js:不可能在全局变量中使用回调结果?
EN

Stack Overflow用户
提问于 2017-02-12 11:08:42
回答 1查看 197关注 0票数 0

我知道这个问题已经被问了很多次了,但是现在我已经用了19.5个小时在这个问题上没有任何结果,我不能指望我自己能做到这一点。我在网上到处搜索指南和小贴士,但这似乎是不可能的。我尝试过承诺和一切,但这是行不通的。

百万互联网络给帮手。

我到底想做什么?

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

对于beta测试,我只在提示符下运行代码(“节点自动”)。

AUTO.JS:

调用node-tesseract模块的auto.js具有:

代码语言:javascript
复制
var tesseract = require('node-tesseract');

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

代码语言:javascript
复制
    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

代码语言:javascript
复制
'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;
    });
EN

回答 1

Stack Overflow用户

发布于 2017-02-12 14:36:39

更新的代码/现在正在工作

代码语言:javascript
复制
      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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42186836

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档