I am having an issue with Node.js and module.exports
. I understand that module.exports
is a call to return an object, that object having whatever properties it is assigned.
If I have a file structure like this:
// formatting.js
function Format(text) {
this.text = text;
}
module.exports = Format;
with this:
// index.js
var formatting = require('./formatting');
Is there a way to initialize a Format
object and use it like this?
formatting('foo');
console.log(formatting.text);
Whenever I try to do it that way, I get an error that says formatting is not a function
. I then have to do it like this:
var x = new formatting('foo');
console.log(x.text);
which seems cumbersome.
In modules like keypress
and request
, they can be used right out of the gate, like this:
var keypress = require('keypress');
keypress(std.in);
or
var request = require('request);
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
How does this work?