Srinesh Srinesh - 5 months ago 11
Node.js Question

Requiring a Javascript file in another JavaScript file

var FS = require('fs');
var Path = require('path');
var Jsonfile = require('jsonfile');

var search = function () {};

search.prototype.projectContainerDirPath = null;

/*
* interface
*/
search.prototype.setPaths = function () {
this.projectContainerDirPath = Path.join(__dirname, '../projects');
};

module.exports.search = search;


This is my
a.js
file. In this file, I have created an object called
search
and added a variable and a function to its prototype. Finally i have exported the search object.

I have
b.js
file which
require
,
a.js
file.
b.js
file is shown below

var search = require("./search");
search.setPaths();


What i'm trying to here is to use all the functions and variables of
a.js
inside
b.js
. But when
b.js
is run, Node JS returns below error

TypeError: search.setPaths is not a function


I tried exporting a new object of
search
.

var obj = new search();
module.exports.search = obj;


And again creating a new object of
search
in file
b.js


var search = require("./a");
var obj = new search();
search.setPaths();


But those two attempts was failed. The reason why I'm using prototype is, there are some more objects that inherits the prototype of
search
object. So is there any way i can export this
search
object and use it in another JavaScript file?

Answer

Try this:

module.exports = search;

And looks like 'search function' is constructor, so you should better use first character as capital to distinguish that this is a Function or Constructor like this:

var Search = function() { ... }
var obj = new Search();

** UPDATED **

Ok, I read your question again, I found wrong point. In search.js file:

var search = function() {};
module.exports = search;   // module.exports.search and this syntax is same

search is a constructor, not an object. In b.js file, you are using search's prototype function setPaths, but search is a just function object that means it connected Function.prototype not search.prototype. If you want to using the prototype function directly from different file, you should export instantiated Object, not a constructor:

var search = function() {};
module.exports = new search();

this is what I did and it works 100%:

// server.js
var search = function() {};
search.prototype.setPaths = function() { ... };
module.exports = new search;  // you can skip () if argument is empty

and this is b.js:

// b.js
var search = require("./search");
search.setPaths();