public
Last active

Can't use _ globally in node REPL

  • Download Gist
index.js
JavaScript
1 2 3
global._ = require('underscore');
 
require('./some-script')();
some-script.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
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;

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.

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.

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.

@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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.