Node module.exports returns undefined

I have a problem with Node.js and module.exports. I understand that module.exportsthis is a call to return an object, this object has any properties that are assigned to it.

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 an object Formatand use it like this:

formatting('foo');
console.log(formatting.text);

Whenever I try to do this, I get an error formatting is not a function. Then I have to do it like this:

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

which seems bulky.

The modules such as keypressand requestthey can be used directly from the gate, for example:

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 it works?

+4
source share
3

new , :

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

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

module.exports = formatting;

, :

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


Edit

request, , JavaScript . , . , request, , . , , ( ) request. , request(blah, blah).pipe(blah).on(blah). , request, . , , ( ). , , :

function hey(){
  return;
}

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

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

, , .

+3
module.exports = Format;

Format, require('./formatting')

, Format, :

module.exports = new Format();
+2

Try the following:

module formatting:

function Format() {
    this.setter = function(text) {
      this.text = text;
    }
    this.show = function() {
      console.log(this.text);
    } 
}
//this says I want to return empty object of Format type created by Format constructor.

module.exports = new Format();

index.js

var formatting = require('./formatting');
formatting('Welcome');
console.log(formatting.show());
+1
source

Source: https://habr.com/ru/post/1622041/


All Articles