如何将数据从JSON保存到NodeJS中的变量

How to save data from JSON to a variable in NodeJS

本文关键字:NodeJS 变量 保存 JSON 数据      更新时间:2023-09-26

我是Node.js的新手,我有一个问题。

我想保存数据从JSON对象,我已经从github API下载。

var http = require("http");
var express = require('express');
var app = express();
var github = require('octonode');
var client = github.client();
app.set('port', process.env.PORT || 8000);
var server = app.listen(app.get('port'), function() {
   console.log('Express server listening on port ' + server.address().port);
});
app.get('/getUsers', function (req, response) {
   response.writeHead(200, {'Content-Type': 'text/json'});
   var result;
   client.get('/users/angular/repos', {}, function (err, status, body, headers) { 
       result = response.write(JSON.stringify(body));
       console.log(result); //JSON object
       return result;
});
console.log(result); //undefined
});

如何保存数据从对象到单个变量?

(然后我想将其转换为数组并获取一些有用的数据)

您将无法在异步调用之外获得结果,因为它尚未定义。要获得这个值,可以调用query的回调函数中的方法,或者使用async模块并传递它。

app.get('/getUsers', function (req, response) {
   response.writeHead(200, {'Content-Type': 'text/json'});
   var result;
   client.get('/users/angular/repos', {}, function (err, status, body, headers) { 
       result = response.write(JSON.stringify(body));
       console.log(result); //JSON object
       doSomeOperationOnResult(result)
});
});
function doSomeOperationOnResult(result){
//Your operating code
}