[node.js] Using the Underscore module with Node.js

I've been learning about node.js and modules, and can't seem to get the Underscore library to work properly... it seems that the first time I use a function from Underscore, it overwrites the _ object with the result of my function call. Anyone know what's going on? For example, here is a session from the node.js REPL:

Admin-MacBook-Pro:test admin$ node
> require("./underscore-min")
{ [Function]
  _: [Circular],
  VERSION: '1.1.4',
  forEach: [Function],
  each: [Function],
  map: [Function],
  inject: [Function],
  (...more functions...)
  templateSettings: { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g },
  template: [Function] }
> _.max([1,2,3])
3
> _.max([4,5,6])
TypeError: Object 3 has no method 'max'
    at [object Context]:1:3
    at Interface.<anonymous> (repl.js:171:22)
    at Interface.emit (events.js:64:17)
    at Interface._onLine (readline.js:153:10)
    at Interface._line (readline.js:408:8)
    at Interface._ttyWrite (readline.js:585:14)
    at ReadStream.<anonymous> (readline.js:73:12)
    at ReadStream.emit (events.js:81:20)
    at ReadStream._emitKey (tty_posix.js:307:10)
    at ReadStream.onData (tty_posix.js:70:12)
> _
3

When I make Javascript files myself and import them, they seem to be working properly. Maybe there's something special with the Underscore library?

This question is related to node.js module underscore.js

The answer is


The Node REPL uses the underscore variable to hold the result of the last operation, so it conflicts with the Underscore library's use of the same variable. Try something like this:

Admin-MacBook-Pro:test admin$ node
> _und = require("./underscore-min")
{ [Function]
  _: [Circular],
  VERSION: '1.1.4',
  forEach: [Function],
  each: [Function],
  map: [Function],
  inject: [Function],
  (...more functions...)
  templateSettings: { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g },
  template: [Function] }
> _und.max([1,2,3])
3
> _und.max([4,5,6])
6

Or :

    var _ = require('underscore')._;

The name _ used by the node.js REPL to hold the previous input. Choose another name.


As of today (April 30, 2012) you can use Underscore as usual on your Node.js code. Previous comments are right pointing that REPL interface (Node's command line mode) uses the "_" to hold the last result BUT on you are free to use it on your code files and it will work without a problem by doing the standard:

var _ = require('underscore');

Happy coding!


Note: The following only works for the next line of code, and only due to a coincidence.

With Lodash,

require('lodash');
_.isArray([]); // true

No var _ = require('lodash') since Lodash mysteriously sets this value globally when required.


Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to module

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7 How to import functions from different js file in a Vue+webpack+vue-loader project Typescript ReferenceError: exports is not defined ImportError: No module named tensorflow ModuleNotFoundError: What does it mean __main__ is not a package? ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import module.exports vs. export default in Node.js and ES6 What's the difference between an Angular component and module Export multiple classes in ES6 modules Python - Module Not Found

Examples related to underscore.js

Add property to an array of objects Comparing two arrays of objects, and exclude the elements who match values into new array in JS using lodash .groupBy. how to add your own keys for grouped output? Remove Duplicate objects from JSON Array Lodash .clone and .cloneDeep behaviors find the array index of an object with a specific key value in underscore Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined Map over object preserving keys Remove an item from array using UnderscoreJS Find by key deep in a nested array