所以......我知道这不是正确的方法......但是我有一个我自己进入的盒子,如果我能找到一种方法让“get”请求在节点中同步运行,它看起来最容易导航。 js
是的,我已经尝试过节点同步(看起来应该可以)
情景是这样的
- 从文件中读取参数化字符串(完成,工作正常)
- 递归地标记字符串,将其分块为键和值(完成,工作正常)
- 调用谷歌翻译来翻译每个值(休息!)
- 重新组装参数化字符串并将其写回输出文件(完成,工作正常)
我知道如何调用谷歌翻译(可以很容易地对整个字符串进行调用),但我不知道如何让异步回调的排序与必要的参数化字符串的递归保持一致我有的数据集。
如果我可以使对 Web 服务的调用表现得好像它是同步的,这将很简单。例如
read string (while not EOF)
recurse (get the next token)
translate the fragment (which is done with request.get()
add translated fragment to the current string
assemble translated string
write to file
节点同步示例有效,但我无法使用request.get()
.
有什么建议么?
摘抄
// this function gets passed in a string and recursively pulls out and
// attempts to translate tokens. It needs to do this as the data source
// contains "key" = "fragment" + $(paramter1) + fragment + $(parameter2) etc
function getTokenSegment(sourceString){
s = sourceString; //lazy
// if the string contains a parameter
if (s.indexOf(leadingDelimiter) != -1) {
// extract the tokens...omitted the error checking (which all works)
translatedToken = syncTranslate(token); // <--- THIS IS WHAT I WANT...
parameter = s.substring(token.length+1, s.indexOf(trailingDelimiter)+1);
remainder = s.substring(token.length + parameter.length+1, s.length);
translatedString = translatedString + translatedToken + parameter
// recursive call to get the rest of the string
+ getTokenSegment(remainder);
}
else {
// the remainder of the string can be translated intact
translatedToken = syncTranslate(s);
translatedString = translatedString + translatedToken;
}
return (translatedString);
}
function syncTranslate(stringToTranslate) {
var sync = require('sync');
sync(function(){
var result = translate.sync(null, {key: key, q: stringToTranslate, target: language});
})
return result;
}
// translate module is from Mike Holly -- https://github.com/mikejholly/node-google-translate
// and worked perfectly when I used it on non-parameterized strings. only edit is the NULL as the
// first parameter in the callback, copied from the node-sync simple example]
var request = require('request')
, _ = require('underscore')
, querystring = require('querystring')
, util = require('util')
module.exports = function(opts, callback) {
// parse & default the arguments
opts = _.defaults(opts, {
source: 'en',
target: 'fr',
key: 'secret',
sourceText: 'text'
});
var url = 'https://www.googleapis.com/language/translate/v2?' + querystring.stringify(opts);
request.get(url, function(err, response, body){
if (err) throw err;
// parse the returned JSON
var json = JSON.parse(body);
if (json.error) {
throw json.error.message;
}
var strings = util.isArray(opts.sourceText) ? opts.sourceText : [opts.sourceText];
var result = {};
var translatedString = '';
strings.forEach(function(original, i){
result[original] = json.data.translations[i].translatedText;
translatedString = result[original];
});
callback(null, translatedString);
});
};