Have you exported your function?
In your module:
module.exports = $$;
In another file
var $$ = require("myModule");
console.log($$("test"));
Domanda
I'm building my first node module, and I'm hoping to get something akin to jQuery
$(searchItem)
so the code could look something like
var $$ = require("myModule"); $$(search).doAction();
and the like, rather than
$$.doAction(search);
Is it possible to return a "root function" like this in a module? Are than any dangers in doing so?
------------------Update Laurent says it's doable as Underscore does it, and that it's safe, now for the how??----------------------------------
I've updated my code to my module starting with a self-referencing function (copied underscore)
(function(){ var fs = require("fs"); console.log("starting"); var root = this; var config =JSON.parse(fs.readFileSync("./config.json")); var $$ = function(obj){ if(!obj){ return config; } else { return obj; } } }).call(this)
Then in my js page
require("myModule"); console.log($$("test"));
Hoping the the console would log "test", but unfortunately I'm getting $$("test")
is not a function.
------------------------------------ update -------------------------------------------
As jtblin pointed out in the answers below, exporting module.exports = $$
works for outputing "test" as test is being passed to the function, but I can't chain methods as per the original example. Part way there though.
Soluzione
Have you exported your function?
In your module:
module.exports = $$;
In another file
var $$ = require("myModule");
console.log($$("test"));
Altri suggerimenti
Underscore is one of the most widely used node.js modules and it does exactly that, so it's pretty safe.