silverwind
silverwind

Reputation: 3921

node.js modules - exporting both the object and it's properties as functions

I'd like to have a module which exports functions like this:

var log = require("log.js");
log("hello");       // should run console.log("hello")
log.info("world");  // should run console.log("world")

What would the contents of log.js be to achieve this? I've tried tampering with the module.exports object but can't seem to achieve this functionality.

Upvotes: 1

Views: 45

Answers (2)

thefourtheye
thefourtheye

Reputation: 239503

function logger (data) {
    console.log(data);
}

logger.info = function (data) {
    console.log(data);
}

exports = module.exports = logger;

Instead of writing the same function again, you can also do

logger.info = logger;

If you are interested to know more about module.exports and exports, read this blog entry of mine.

Upvotes: 4

Jentel
Jentel

Reputation: 154

exports.log = function(msg) { 
    console.log(msg);
}
exports.info = function(msg) {
    console.log(msg);
}

Another way of doing it.

Upvotes: 0

Related Questions