Skip to content

Instantly share code, notes, and snippets.

@lancejpollard
Created July 31, 2012 20:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lancejpollard/3220108 to your computer and use it in GitHub Desktop.
Save lancejpollard/3220108 to your computer and use it in GitHub Desktop.
Can't use _ globally in node REPL
global._ = require('underscore');
require('./some-script')();
console.log('some-script required', _.toString()); // "function (obj) { return new wrapper(obj); }"
asyncMethod = function(callback) {
console.log('asyncMethod start');
process.nextTick(function() {
console.log('asyncMethod complete');
callback();
});
console.log('asyncMethod returning');
return 'a string';
}
mainMethod = function() {
var callback = function() {
console.log('mainMethod callback', _.toString()) // ERROR
};
var result = asyncMethod(callback);
console.log('mainMethod result', result);
};
module.exports = mainMethod;
@edubkendo
Copy link

Don't know if you knew this already or not, but in some (most? all?) REPL's "_" represents the return value of the last statement, So that you can do cool stuff like:

2 + 2
a = _
console.log a # 4

So if this is the case in node's REPL (and it is in coffee, so it probably is), it would explain what seems like screwy behavior from the underscore variable.

@lancejpollard
Copy link
Author

Yeah it's nice to be able to do that a = _, but that means you can't globally set underscore, so you'll have to do this in every module :/

// where global._ == require('underscore') in tower
_ = global._ // var _ = global._

Otherwise you'd have to do stuff like this:

class App.Post extends Tower.Model
  @field 'title'
  @field 'slug'

  @before 'save', 'setSlug'

  setSlug: ->
    # at some point in execution, if inside `tower console` or some REPL,
    # `_` will be the last returned value rather than the module.
    @set 'slug', Tower.modules._.parameterize(@get('title'))

... which isn't ideal.

@lancejpollard
Copy link
Author

@edubkendo
Copy link

yeah i see how that could get really old. It was certainly worth a shot to try to sell them on making it configurable, and I wish they would have given a reason/case where it was or could have caused a problem. But then, the philosophy? of node-core does seem to be rather conservative, which makes sense. Would have been nice though, given underscore is such an essential library.

@jasoncrawford
Copy link

@viatropos I had this problem too, so I figured out how to solve it using the Node repl module: https://gist.github.com/jasoncrawford/6818650

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment