关于nodejs中变的全局变量,局部变量问题
发布于 13 年前 作者 bao00long 13330 次浏览 最后一次编辑是 8 年前

最近在学nodejs和express,今天在看https://github.com/visionmedia/express/blob/master/examples/github/app.js 这个程序的源代码的时候,觉得看起来挺费劲的就动手改成了我理解的代码` /**

  • Module dependencies. */

var express = require(’…/…/lib/express’) , http = require(‘http’);

var app = express();

// Expose our views

app.set(‘views’, __dirname + ‘/views’); app.set(‘view engine’, ‘jade’);

/**

  • Request github json api path.
  • @param {String} path
  • @param {Function} fn
  • @api public */

function request(path, fn){ var client = http.createClient(80, ‘github.com’) , req = client.request(‘GET’, ‘/api/v2/json’ + path, { Host: ‘github.com’ });

req.on(‘response’, function(res){ res.body = ‘’; res.on(‘data’, function(chunk){ res.body += chunk; }); res.on(‘end’, function(){ try { //console.log(JSON.parse(res.body)); fn(null, JSON.parse(res.body)); } catch (err) { fn(err); } }); }); req.end(); }

/**

  • Sort repositories by watchers desc.
  • @param {Array} repos
  • @api public */

function sort(repos){ return repos.sort(function(a, b){ if (a.watchers == b.watchers) return 0; if (a.watchers > b.watchers) return -1; if (a.watchers < b.watchers) return 1; }); }

/**

function totalWatchers(repos) { return repos.reduce(function(sum, repo){ return sum + repo.watchers; }, 0); }

/**

  • Default to my user name :) */

app.get(’/’, function(req, res){ res.redirect(’/repos/visionmedia’); });

/**

  • Display repos. */

    var users = []; app.get(’/repos/*’, function(req, res, next){ var names = req.params[0].split(’/’);

    for(var i=0;i<names.length;i++){ fetchData(names[i]); } console.log(users); console.log(’… done’); res.render(‘index’, { users: users }); }); function fetchData(name){ // We have a user name if (name) { console.log(’… fetching \x1b[33m%s\x1b[0m’, name); request(’/repos/show/’ + name, function(err, user){ user.totalWatchers = totalWatchers(user.repositories); user.repos = sort(user.repositories); user.name = name; users.push(user); }); } }

// Serve statics from ./public app.use(express.static(__dirname + ‘/public’));

// Listen on port 3000 app.listen(3000); console.log(‘Express app started on port 3000’);

但是运行之后打印不出来users数组的值,users数组不是页面全局变量吗,我已经往里面push值了呀 但是为啥没有呢,求解 `

2 回复

自己顶

水帖, 求按 markdown 排版…

回到顶部