Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
7
rated 0 times [  12] [ 5]  / answers: 1 / hits: 22607  / 9 Years ago, tue, december 29, 2015, 12:00:00

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?


More From » node.js

 Answers
21

I'd suggest wrapping the new call in it's own function then returning that:



function Format(text) {
this.text = text;
}

function formatting(text) {
return new Format(text);
}

module.exports = formatting;


This way you should still be able to do:



var format = formatting('foo');
console.log(format.text);




Edit:



In terms of the request stuff, one thing you have to remember is that in JavaScript, functions are still objects. This means you can still add properties and methods to them. This is what they're doing in request though overall it's a bit too complicated to explain every detail in this answer. From what I can tell, they add a bunch of methods (functions on an object) to the request function. This is why you can immediately call those methods like request(blah, blah).pipe(blah).on(blah) Based on what's returned from calling the request function, you can chain some of the other methods on the back of it. When you're using request it's not an object, it's a function (but still technically an object). To demonstrate how functions are still objects and how it's possible to add methods to them, check out this simple example code:



function hey(){
return;
}

hey.sayHello = function(name) {
console.log('Hello ' + name);
}

hey.sayHello('John'); //=> Hello John


This is basically what they're doing, just a lot more complicated and with a lot more stuff going on.


[#63913] Saturday, December 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
noa

Total Points: 579
Total Questions: 83
Total Answers: 93

Location: Sweden
Member since Mon, Aug 10, 2020
4 Years ago
;