JavaScript函数数据处理

JavaScript函数数据处理,javascript,function,Javascript,Function,我是javascript的新手,现在我需要做一件小事。 我有这个密码 http.get(options, function(res) { res.setEncoding('utf-8') res.on('data', function (chunk) { var parser = new xml2js.Parser(); if(chunk.length < 50) { console.log('end!');

我是javascript的新手,现在我需要做一件小事。 我有这个密码

http.get(options, function(res) {
    res.setEncoding('utf-8')
    res.on('data', function (chunk) {
        var parser = new xml2js.Parser();
        if(chunk.length < 50) {
            console.log('end!');
        } else {
            console.log(chunk);
        }
    });
})
http.get(选项、函数(res){ res.setEncoding('utf-8') res.on('data',函数(块){ var parser=new xml2js.parser(); if(chunk.length<50){ console.log('end!'); }否则{ console.log(块); } }); })
我需要在剩下的代码中使用变量“chunk”进行操作。如何从函数中抛出它?-当然,statdart return在这里不起作用。

您可以将其设置为包含范围中的变量

var ch;
http.get(options, function(res) {
    res.setEncoding('utf-8')

    res.on('data', function (chunk) {

    var parser = new xml2js.Parser();
    if(chunk.length < 50) {
        ch = chunk;
    } else {
        console.log(chunk);
    }
});
编辑:

要在nodejs中设置全局变量(这是不推荐的),您可以使用
全局
对象:

GLOBAL.chunk = chunk;

再次,这不必要,考虑更改代码,以便不必使用全局变量。

您可以将其设置为包含范围中的变量。

var ch;
http.get(options, function(res) {
    res.setEncoding('utf-8')

    res.on('data', function (chunk) {

    var parser = new xml2js.Parser();
    if(chunk.length < 50) {
        ch = chunk;
    } else {
        console.log(chunk);
    }
});
编辑:

要在nodejs中设置全局变量(这是不推荐的),您可以使用
全局
对象:

GLOBAL.chunk = chunk;

再次,这不必要,考虑改变你的代码,这样你就不必使用GULARS了。< /P>但是变量CH仍然无法从函数内容中获得!我想在整个代码中使用它!您没有在问题中指定nodejs。但是变量ch在函数内容之外仍然不可用!我想在整个代码中使用它!您的问题中没有指定nodejs。