module.exports is not returning functions in nodejs - node.js

Everyone I'm beginner in NODE.JS i'm using module.exports function inside that I have written hello function in it.I tried to import from other file.but it's not working.Can anyone solve this problem.Thanks in advance...
index.js
module.exports=function(){
hello:(data)=>{
return "Good night" +data;
}
}
trail.js
const index=require('./index');
const e=new index();
console.log(e.hello("abc"));

When you're using a function as a constructor, creating new objects from it, you'll have to reference each of those objects with this to assign their properties:
module.exports=function(){
this.hello = (data) => {
return "Good night" +data;
};
}
The syntax <identifier>: has different meanings depending on its placement/surroundings. When used within a function body, at the start of a statement, it only defines a label. To have it define a property, it would have to be used within an object initializer.

I found the solution slightly we have to change the code in index.js.In ES6 Functional constructors are available.we should use this keyword this keywords refers current class objects.because In javascript Functions are first class Objects.correct me If I'm wrong. post the answer if anyone knows Others solution are also always welcome....
Index.js
module.exports=function(){
this.hello=(data)=>{
return "Good night" +data;
}
}
Trail.js
const index=require('./index');
const e=new index();
console.log(e.hello("abc"));

you can also use it this way:
module.exports=function(data){
return "Good night" +data;
}
const temp = require('./index');
console.log(temp('demo developer'));

I dont know what is the correct desicion you tring to find out, but may be you would like to go this way:
index.js:
exports.hello = data => {
return 'Good night ' + data;
};
trail.js:
const e = require('./index');
console.log(e.hello('Jhonny'));

Related

Node js - Issue with my syntax in require(module) . When to use {} and when not to use {} in require('module')

I have a query with the syntax in the require statement. Please refere the sample code below.
const nodemailer = require("nodemailer");
const {google} =require('googleapis');
const {OAuth2}=google.auth;
Some times , I see sample codes which use
const {<variable>} = require('moduleName')
Other times, I see like below
const <variable> = require('moduleName')
What is the difference between them?
Thanks in Advance.
Grateful to the Developers Community.
So, you use { } in this context when you want to do object destructuring to get a property from the exported object and create a module-level variable with that same name.
This:
const { google } = require('googleapis');
is a shortcut for this:
const __g = require('googleapis');
const google = __g.google;
So, within this context, you use the { google } only when you want the .google property from the imported module.
If you want the entire module handle such as this:
const nodemailer = require("nodemailer");
then, you don't use the { }. The only way to know which one you want for any given module is to consult the documentation for the module, the code for the module or examples of how to use the module. It depends entirely upon what the module exports and whether you want the top level export object or you want a property of that object.
It's important to realize that the { } used with require() is not special syntax associated with require(). This is normal object destructuring assignment, the same as if you did this:
// define some object
const x = { greeting: "hello" };
// use object destructuring assignment to create a new variable
// that contains the property of an existing object
const { greeting } = x;
console.log(greeting); // "hello
When you import the function with {}, it means you just import one function that available in the package. Maybe you have've seen:
const {googleApi, googleAir, googleWater} = require("googleapis")
But, when you not using {}, it means you import the whole package, just write:
const google = require("googleapis")
So, let say when you need googleApi in your code. You can call it:
google.googleApi

Is it possible to one method into another file in nodejs and express?

how can I use one method into entire project is it possible?
If it's possible please help me with detail.
Thanks Advance
As an example its your log.js file.You can use module.exports to export a function like this
module.exports.log = function (msg) {
console.log(msg);
};
Now if you want to import it in ,suppose app.js file.Just do something like this.
var msg = require('./Log.js');// the path is important here
msg.log('Hello World');
In above example you are exporting log function ,import it with the way I told and you can use it anywhere you want (after requiring).
Better have a look at the docs too.
You can also use ES6 export and import,something like below
export function log(){ } // exports named function log
import { log } from '..filepath/filename'
MDN docs ,describe it elaborately.

What is exports.install in node js?

Hi I found a framework where they use a lot this pattern.
exports.install = function(){
//code
}
but usually you see this pattern in nodejs
module.exports = {
//code
}
Is this the same thing or is this something else ?
exports is the object corresponding to module.exports before you do anything to it. I think it's due to some legacy code, but basically folks use module.exports if they want to replace the whole object with their own object or a function, while they use exports if they just want to hang functions off the module. It's a little confusing at first, but essentially exports.install just means that calling code would do something like:
const mod = require('that-module');
mod.install(params, callback); // call that function
The framework you're looking at is probably using it as part of a bootstrapping process, afaik it doesn't have significance to the node engine itself.
Yes, it is the same thing. You can use one of 2 ways to setup your code.
The different thing is memory. They point to same memory. You can think exports like a variable and you can not use this way to export your module:
Given this module:
// test.js
exports = {
// you can not use this way to export module.
// because at this time, `exports` points to another memory region
// and it did not lie on same memory with `module.exports`
sayHello: function() {
console.log("Hello !");
}
}
The following code will get the error: TypeError: test.sayHello is not a function
// app.js
var test = require("./test");
test.sayHello();
// You will get TypeError: test.sayHello is not a function
The correct way you must use module.exports to export your module:
// test.js
module.exports = {
// you can not use this way to export module.
sayHello: function() {
console.log("Hello !");
}
}
// app.js
var test = require("./test");
test.sayHello();
// Console prints: Hello !
So, it just is style of developer.

Exporting a prototype in node.js: module.exports=Prototype or exports.Prototype=Prototype?

What is the preferred way to export a prototype in node.js? You can take two approaches:
Export the prototype itself
function A () {
}
module.exports = A;
which is used as:
var A = require('./A.js');
var a = new A();
Export an object containing the prototype as property
function A () {
}
exports.A = A;
which is used as:
var A = require('./A.js').A;
var p = new A();
The first solution looks much more convenient to me, though I know there are concerns about replacing the exports object. Which of the two is best to use and why?
The second one would only be useful if you exported multiple classes from one file which is something that is questionable by itself.
There is no problem in replacing the exports object at all.

What is the best way to expose methods from Node.js?

Consider I want to expose a method called Print
Binding method as prototype:
File Saved as Printer.js
var printerObj = function(isPrinted) {
this.printed = isPrinted;
}
printerObj.prototype.printNow = function(printData) {
console.log('= Print Started =');
};
module.exports = printerObj;
Then access printNow() by putting code require('Printer.js').printNow() in any external .js node program file.
Export method itself using module.exports:
File Saved as Printer2.js
var printed = false;
function printNow() {
console.log('= Print Started =');
}
module.exports.printNow = printNow;
Then access printNow() by putting code require('Printer2.js').printNow() in any external .js node program file.
Can anyone tell what is the difference and best way of doing it with respect to Node.js?
Definitely the first way. It is called the substack pattern and you can read about it on Twitter and on Mikeal Rogers' blog. Some code examples can be found at the jade github repo in the parser:
var Parser = exports = module.exports = function Parser(str, filename, options){
this.input = str;
this.lexer = new Lexer(str, options);
...
};
Parser.prototype = {
context: function(parser){
if (parser) {
this.contexts.push(parser);
} else {
return this.contexts.pop();
}
},
advance: function(){
return this.lexer.advance();
}
};
In the first example you are creating a class, ideally you should use it with "new" in your caller program:
var PrinterObj = require('Printer.js').PrinterObj;
var printer = new PrinterObj();
printer.PrintNow();
This is a good read on the subject: http://www.2ality.com/2012/01/js-inheritance-by-example.html
In the second example you are returning a function.
The difference is that you can have multiple instances of the first example (provided you use new as indicated) but only one instance of the second approach.

Resources