1078

Let's say I have a file called app.js. Pretty simple:

var express = require('express');
var app = express.createServer();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(req, res){
  res.render('index', {locals: {
    title: 'NowJS + Express Example'
  }});
});

app.listen(8080);

What if I have a functions inside "tools.js". How would I import them to use in apps.js?

Or...am I supposed to turn "tools" into a module, and then require it? << seems hard, I rather do the basic import of the tools.js file.

TIMEX
  • 217,272
  • 324
  • 727
  • 1,038
  • 4
    What threw me off here was `require`ing a folder in the same directory on Windows. You've got to use unix-style addressing: `./mydir` instead of plain old `mydir`. – Ben Aug 03 '14 at 14:03
  • 1
    I created a module to import scripts, export to file, and include module from outside `node_modules` folder. https://www.npmjs.com/package/node-import Hope it can help. Thanks! – Nanang Mahdaen El-Agung Mar 21 '15 at 23:54

25 Answers25

1551

You can require any js file, you just need to declare what you want to expose.

// tools.js
// ========
module.exports = {
  foo: function () {
    // whatever
  },
  bar: function () {
    // whatever
  }
};

var zemba = function () {
}

And in your app file:

// app.js
// ======
var tools = require('./tools');
console.log(typeof tools.foo); // => 'function'
console.log(typeof tools.bar); // => 'function'
console.log(typeof tools.zemba); // => undefined
Taysky
  • 4,132
  • 2
  • 16
  • 26
masylum
  • 20,309
  • 3
  • 16
  • 20
  • 111
    +1 Nicely done, even confines the imported code to it's own namespace. I'll have to make a note of this for later. – Evan Plaice Jan 20 '12 at 23:35
  • 8
    I wonder if it's possible to import external scripts. `require("http://javascript-modules.googlecode.com/svn/functionChecker.js")` doesn't seem to import the module correctly. Is there any other way to import external scripts? – Anderson Green Jan 01 '13 at 22:57
  • 6
    And what if I have to pass variable into function Like, bar: function(a, b){ //some code } – Nishutosh Sharma May 24 '13 at 18:53
  • Like `zemba` in place of baz – JSmyth Oct 14 '13 at 10:31
  • 5
    Since you are exposing properties I would use exports instead of module.exports. For exports vs module.exports : http://stackoverflow.com/questions/5311334/what-is-the-purpose-of-nodejs-module-exports-and-how-do-you-use-it – Farm Dec 15 '13 at 03:21
  • This post should be marked as the correct answer imo. Nice. – dot slash hack Apr 09 '14 at 18:41
  • How to run initialization code in the require() call? – cprcrack May 20 '14 at 13:14
  • 4
    how to call function bar() ,inside foo() function, means how to access one function withn another – pitu Aug 08 '14 at 07:05
  • Used `var SomeClass = ... ; module.exports = SomeClass; – Saltymule Jun 18 '15 at 16:05
  • `you can require any js file` seems inconsistent with requirement for it to be formatted as per `foo()` and `bar()` – geotheory Feb 04 '16 at 12:42
  • Answer states usage as tools.foo; I found that the function HAS to have the parentheses at the end like tools.foo(); Took me an hour to figure that out as it kept returning NaN. :-) – Norman Bird Jun 30 '16 at 23:59
  • Where do you put global variables in this tools.js script? Above the 'module.exports = {' part? – F3L1X79 Sep 12 '16 at 15:32
  • 1
    @pitu use ```this.``` e.g. ```console.log(typeof this.bar);``` – ow3n Sep 29 '16 at 15:00
  • 1
    A note to newbies who are like me, the functions definitions in the module are separated by commas, not by semicolons or just new lines. – CodeBrew May 14 '17 at 01:40
  • in case anyone battles when they have a folder like 'src/myFile' - you need to do: require (./src/myFile'). – Rowan Gontier Apr 19 '18 at 00:45
  • a bit late, but how do I call zemba() function inside foo()? – DaveO Dec 05 '19 at 08:53
  • What does the syntax inside the module.exports do? On first it seems like I should replace "function ()" with the name of the function inside this module, so that there is a set of exposed function names correlated to a set of function calls on the right, e.g. `foo: somefunc()`. Why would anyone EVER let a language *define* a function within the context of an export statement? That is insane. The fact that a function is declared using `myfunc: function () { code goes here }` is also insane. You should never have to write "function ()" explicitly to declare a function. *~scratching head* – Ryan Dec 06 '19 at 23:16
  • to call another function within the `tools.js`, use `this.foo()` if called from `bar()` function as mentioned above. note that if i `console.log(this.foo())` it will output `undefined` but it will output whatever it has `console.log()` in `foo()` – Andrew Oct 17 '20 at 19:19
  • Your solution for `tools.js`(module.exports={}` seems similar to `exports.myfun = function(){}` – Timo Apr 07 '21 at 07:54
317

If, despite all the other answers, you still want to traditionally include a file in a node.js source file, you can use this:

var fs = require('fs');

// file is included here:
eval(fs.readFileSync('tools.js')+'');
  • The empty string concatenation +'' is necessary to get the file content as a string and not an object (you can also use .toString() if you prefer).
  • The eval() can't be used inside a function and must be called inside the global scope otherwise no functions or variables will be accessible (i.e. you can't create a include() utility function or something like that).

Please note that in most cases this is bad practice and you should instead write a module. However, there are rare situations, where pollution of your local context/namespace is what you really want.

Update 2015-08-06

Please also note this won't work with "use strict"; (when you are in "strict mode") because functions and variables defined in the "imported" file can't be accessed by the code that does the import. Strict mode enforces some rules defined by newer versions of the language standard. This may be another reason to avoid the solution described here.

Community
  • 1
  • 1
Udo G
  • 11,022
  • 11
  • 47
  • 77
  • 44
    Cool, this is useful for quick'n'dirty putting JS libs designed for client-side into a node.js app without the need of maintaining a Node-styled fork. – Kos Dec 11 '11 at 13:24
  • 1
    The "+''" is just a shortcut to force string casting. The more readable solution would be "String(fs.readFileSync('tools.js'))" or if the read.FileSync returns an object then "fs.readFileSync('tools.js').toString()" should also work since toString is attached to the base Object prototype (i.e Object.prototype.toString). – Evan Plaice Jan 20 '12 at 23:22
  • Blindly importing JS into the global namespace can open the code to unintended naming conflicts. If the code in the tools.js file were written in object literal format you could assign them to a local variable which works like a pseudo-namespace. Also, I don't really think the eval is required (masylum's code makes it seem like the code is already eval'd during the require). I think you're import/eval-ing the code with require, casting that code back to string and eval-ing it again just to pidgeonhole it into the global namespace. Looks like you're doing it wrong. – Evan Plaice Jan 20 '12 at 23:31
  • 19
    I just answered the original question, which is about including code, not writing modules. The former *can* have advantages in certain situations. Also, your assumption about require is wrong: The code is certainly eval'd, but it remains in it's own namespace and has no way to "pollute" the namespace of the calling context, hence you need to eval() it yourself. In most cases using the method described in my anwer *is bad practice* but it's not me that should decide if it is for TIMEX. – Udo G Jan 21 '12 at 17:03
  • 15
    @EvanPlaice: do you have a better suggestion **which actually answers the question**? If you need to include a file *which is not a module*, do you have a better approach than this? – jalf Apr 21 '12 at 11:04
  • 9
    There are sometimes when you need include, and sometimes require, they are two fundamentally different concepts in most programming languages, Node JS as well. The ability to include js in place should be a part of Node to be honest, but eval'ing it is essentially a decent solution. Upvoted. – J. Martin Jun 10 '12 at 10:16
  • I would like to use require, but then I can't use John Resig's simple inheritance code (unless I'm mistaken/someone has a solution without using readFileSync) – Nick Jun 26 '12 at 08:19
  • This worked for me and I simply wanted to consume a manually set variable in a global which is share with the client side app. +1 – sidonaldson Nov 07 '13 at 16:23
  • 4
    Note that is incompatible with __use strict__ - as __use strict__ will constrain the use of eval by blocking introduction of new variables through eval, etc. – timbo Feb 03 '14 at 23:41
  • Cool trick but this works as long as `tools.js` does not depend on any other JS file. However if `tools.js` needs `foo.js`, this approach will fail (assuming you do not want to put eval/readFileSync inside tools.js too) – user Dec 01 '14 at 05:25
  • I liked this approach. I just wrapped a function call around it like this, though: function(inc) { eval(fs.readFileSync(inc, 'utf-8').toString()); } And then it's called like this: include('./routes/admin.inc.js'); I like renaming include files so that they're not mistaken by someone else as stand-alone. – Michael Blankenship Mar 13 '15 at 00:47
  • @MichaelBlankenship: Sorry, but that won't really work. Such an `include` function creates a new scope so you won't be able to access global variables or functions of the included file. – Udo G Mar 13 '15 at 09:38
  • @Udo Hmm... Well, I was able to break up my routes/index.js into several includes: authenticated.inc.js, nonauthenticated.inc.js, admin.inc.js, etc. In this way I can segment the code better so that I'm not paging through lots of it. – Michael Blankenship Mar 22 '15 at 17:42
  • @MichaelBlankenship unless you do some hacky things you didn't mention, then you're creating a [local scope](http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/) this way. That means the `include()` function can't export variables or functions. It can, however, *access* other variables that are accessible to the `include()` function itself, like a router instance, for example - but that's a specific case and does not qualify as a generic include-function. There are some solutions, though - please see the other answers. – Udo G Mar 23 '15 at 09:16
  • Stinks for debugging. When there's an error in the included file, it can't tell what file it came from. – user3413723 Dec 11 '15 at 09:56
  • @Code Bling: that's not correct. `require()` can only provide variables/values and execute code in the module. `eval` can potentially mess with local variables and in non-strict mode even declare new locally scoped variables. I wouldn't recommend eval() either, but the fact is, eval **has** different side effects and can do more (dangerous things) than require() – Udo G Oct 04 '16 at 06:34
  • To be more specific in php include and require handles errors differently. So if you want an equivalent to php's include you will need to surround the require with a try catch block and show a warning – chrmcpn Jul 12 '17 at 16:20
  • @chrmcpn: are you implying that php include transforms exceptions into warnings? I don't think so – Udo G Jul 12 '17 at 21:22
  • It dosn't transform exceptions into warnings but emits a warning instead of an exception as said here: http://php.net/manual/en/function.require.php – chrmcpn Jul 14 '17 at 19:50
  • 1
    To everyone who thinks `eval()` is "dangerous" or "bad" please remember: it's the programmers OWN CODE being evalled. Eval is only dangerous if you don't know what you're running. – Marc Aug 23 '20 at 19:58
199

You need no new functions nor new modules. You simply need to execute the module you're calling if you don't want to use namespace.

in tools.js

module.exports = function() { 
    this.sum = function(a,b) { return a+b };
    this.multiply = function(a,b) { return a*b };
    //etc
}

in app.js

or in any other .js like myController.js :

instead of

var tools = require('tools.js') which force us to use a namespace and call tools like tools.sum(1,2);

we can simply call

require('tools.js')();

and then

sum(1,2);

in my case I have a file with controllers ctrls.js

module.exports = function() {
    this.Categories = require('categories.js');
}

and I can use Categories in every context as public class after require('ctrls.js')()

Community
  • 1
  • 1
Nick Panov
  • 2,287
  • 1
  • 11
  • 8
  • 13
    How does this not have more +1s? This is a real solution to what the question asks (albeit not the 'official' one). It's also a million times easier to debug than eval() because node can give a useful call stack instead pointing to the actual file instead of just undefined. – user3413723 Jun 26 '15 at 05:20
  • But what if you require different js files that use the same function names? Which "sum" will be called if different modules have a 'sum' function? – Kokodoko Oct 15 '15 at 14:37
  • Same as when you overwrite other variables? With require('module.js')(); You actually execute the code from the module in the current scope. It's convenient when you need to import some global scope objects defined as namespaces in the module itself. – Nick Panov Oct 16 '15 at 08:28
  • This trick seems comparable to PHP traits and "from x import y" in Python. Powerful, but should be used with care as it adds external stuff to the scope, so it's easier to break stuff and harder to see where variables actually come from. Usually, it would be better to import methods/properties and use the proper namespacing objects. But a useful trick to know nevertheless! – okdewit Jan 21 '16 at 13:52
  • 6
    Note that you cannot "use 'strict" mode in the imported module. – David Jun 13 '16 at 15:18
  • In some scenarios, it is required to specify a path in the `require` function (i.e. './tools.js') in order to be recognized. – Jaime Jul 05 '16 at 08:37
  • 2
    @Nick Panov: brilliant! It should be worth to note that this works because `this` in a function is the *global scope* when the function is called directly (not bound in any way). – Udo G Oct 04 '16 at 06:48
  • 4
    this just changed my life, no joke -- had a 1000+ line file that I couldn't break up because the variables of different methods are all inter-correlated and would need the requires to be all in the same scope ... `require('blah.js')();` should allow me to import them all into the same scope!!! thanks!!! – Sam Johnson Apr 17 '17 at 19:18
  • 3
    This is a great tip! Caveat: if you declare the module.exports function using the () => {} shortcut syntax rather than the standard function() {} declaration, it fails. Took me an hour to figure out where the problem was! (Arrow functions don't have their own 'this' property: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) – Ryan Griggs Oct 11 '18 at 15:09
  • This method worked on a testing file, not sure why it didn't work on the main project so I switched back to https://stackoverflow.com/a/43341268/1920003 – Lynob Jul 29 '19 at 13:28
131

Create two js files

// File cal.js
module.exports = {
    sum: function(a,b) {
        return a+b
    },
    multiply: function(a,b) {
        return a*b
    }
};

Main js file

// File app.js
var tools = require("./cal.js");
var value = tools.sum(10,20);
console.log("Value: "+value);

Console Output

Value: 30
bhawkeswood
  • 640
  • 7
  • 11
Jayaprakash G
  • 2,387
  • 1
  • 12
  • 8
  • the function declared in other file is there any way to identify the type , i mean while coding when i press . will any ide be able to understand which type of object it is – JustTry Jul 16 '20 at 03:41
52

create two files e.g app.js and tools.js

app.js

const tools= require("./tools.js")


var x = tools.add(4,2) ;

var y = tools.subtract(4,2);


console.log(x);
console.log(y);

tools.js

 const add = function(x, y){
        return x+y;
    }
 const subtract = function(x, y){
            return x-y;
    }
    
    module.exports ={
        add,subtract
    }

output

6
2
YouBee
  • 1,366
  • 10
  • 12
38

Here is a plain and simple explanation:

Server.js content:

// Include the public functions from 'helpers.js'
var helpers = require('./helpers');

// Let's assume this is the data which comes from the database or somewhere else
var databaseName = 'Walter';
var databaseSurname = 'Heisenberg';

// Use the function from 'helpers.js' in the main file, which is server.js
var fullname = helpers.concatenateNames(databaseName, databaseSurname);

Helpers.js content:

// 'module.exports' is a node.JS specific feature, it does not work with regular JavaScript
module.exports = 
{
  // This is the function which will be called in the main file, which is server.js
  // The parameters 'name' and 'surname' will be provided inside the function
  // when the function is called in the main file.
  // Example: concatenameNames('John,'Doe');
  concatenateNames: function (name, surname) 
  {
     var wholeName = name + " " + surname;

     return wholeName;
  },

  sampleFunctionTwo: function () 
  {

  }
};

// Private variables and functions which will not be accessible outside this file
var privateFunction = function () 
{
};
Ivan Koblik
  • 4,195
  • 1
  • 28
  • 32
Placeholder
  • 3,699
  • 6
  • 26
  • 34
36

I was also looking for a NodeJS 'include' function and I checked the solution proposed by Udo G - see message https://stackoverflow.com/a/8744519/2979590. His code doesn't work with my included JS files. Finally I solved the problem like that:

var fs = require("fs");

function read(f) {
  return fs.readFileSync(f).toString();
}
function include(f) {
  eval.apply(global, [read(f)]);
}

include('somefile_with_some_declarations.js');

Sure, that helps.

Community
  • 1
  • 1
jmparatte
  • 377
  • 3
  • 3
  • 2
    I understand how ugly of a hack this is, but it sure helped me out. – lindhe Jan 13 '19 at 20:33
  • New to Node. Seems crazy to me this is what's required simply to inline some JS but this was the only solution that worked for me, thanks. So many answers mentioning modules—unbelievable. – Nomas Prime Jun 09 '20 at 00:43
25

The vm module in Node.js provides the ability to execute JavaScript code within the current context (including global object). See http://nodejs.org/docs/latest/api/vm.html#vm_vm_runinthiscontext_code_filename

Note that, as of today, there's a bug in the vm module that prevenst runInThisContext from doing the right when invoked from a new context. This only matters if your main program executes code within a new context and then that code calls runInThisContext. See https://github.com/joyent/node/issues/898

Sadly, the with(global) approach that Fernando suggested doesn't work for named functions like "function foo() {}"

In short, here's an include() function that works for me:

function include(path) {
    var code = fs.readFileSync(path, 'utf-8');
    vm.runInThisContext(code, path);
}
Chad Austin
  • 402
  • 4
  • 7
  • I found vm.runInThisContext in another SO answer, and had been using it, to include "vanilla" Javascript code files. Then however I tried to use it to include code that depended on node functionality (e.g. "var fs = require('fs')"), and it would not work. In that case however, the "eval" solution(s) noted in a couple of answers, does indeed work. – Dexygen Jun 28 '13 at 20:13
  • Thinking this through a bit more, when you start needing to include code that depends on node functionality, it's probably time to write a module, though the eval solution could be the first step in that process – Dexygen Jul 01 '13 at 13:34
25

say we wants to call function ping() and add(30,20) which is in lib.js file from main.js

main.js

lib = require("./lib.js")

output = lib.ping();
console.log(output);

//Passing Parameters
console.log("Sum of A and B = " + lib.add(20,30))

lib.js

this.ping=function ()
{
    return  "Ping Success"
}
//Functions with parameters
this.add=function(a,b)
    {
        return a+b
    }
Dharmesh
  • 1,590
  • 2
  • 11
  • 12
18

create two files e.g import_funcs.js and main.js

1.) import_funcs.js

// Declaration --------------------------------------

 module.exports =
   {
     add,
     subtract
     // ...
   }


// Implementation ----------------------------------

 function add(x, y)
 {
   return x + y;
 }

 function subtract(x, y)
 {
   return x - y;
 }
    

// ...

2.) main.js

// include ---------------------------------------

const sf= require("./import_funcs.js")

// use -------------------------------------------

var x = sf.add(4,2);
console.log(x);

var y = sf.subtract(4,2);
console.log(y);

    

output

6
2
Ingo
  • 4,676
  • 1
  • 25
  • 22
14

Udo G. said:

  • The eval() can't be used inside a function and must be called inside the global scope otherwise no functions or variables will be accessible (i.e. you can't create a include() utility function or something like that).

He's right, but there's a way to affect the global scope from a function. Improving his example:

function include(file_) {
    with (global) {
        eval(fs.readFileSync(file_) + '');
    };
};

include('somefile_with_some_declarations.js');

// the declarations are now accessible here.

Hope, that helps.

Fernando
  • 149
  • 1
  • 2
11

It worked with me like the following....

Lib1.js

//Any other private code here 

// Code you want to export
exports.function1 = function(params) {.......};
exports.function2 = function(params) {.......};

// Again any private code

now in the Main.js file you need to include Lib1.js

var mylib = requires('lib1.js');
mylib.function1(params);
mylib.function2(params);

Please remember to put the Lib1.js in node_modules folder.

MattC
  • 4,968
  • 1
  • 42
  • 37
M.Hefny
  • 2,369
  • 1
  • 20
  • 22
11

Another way to do this in my opinion, is to execute everything in the lib file when you call require() function using (function(/* things here */){})(); doing this will make all these functions global scope, exactly like the eval() solution

src/lib.js

(function () {
    funcOne = function() {
            console.log('mlt funcOne here');
    }

    funcThree = function(firstName) {
            console.log(firstName, 'calls funcThree here');
    }

    name = "Mulatinho";
    myobject = {
            title: 'Node.JS is cool',
            funcFour: function() {
                    return console.log('internal funcFour() called here');
            }
    }
})();

And then in your main code you can call your functions by name like:

main.js

require('./src/lib')
funcOne();
funcThree('Alex');
console.log(name);
console.log(myobject);
console.log(myobject.funcFour());

Will make this output

bash-3.2$ node -v
v7.2.1
bash-3.2$ node main.js 
mlt funcOne here
Alex calls funcThree here
Mulatinho
{ title: 'Node.JS is cool', funcFour: [Function: funcFour] }
internal funcFour() called here
undefined

Pay atention to the undefined when you call my object.funcFour(), it will be the same if you load with eval(). Hope it helps :)

11

app.js

let { func_name } = require('path_to_tools.js');
func_name();    //function calling

tools.js

let func_name = function() {
    ...
    //function body
    ...
};

module.exports = { func_name };
Kristianmitk
  • 3,057
  • 4
  • 17
  • 38
Ashish Duklan
  • 127
  • 1
  • 4
10

I just want to add, in case you need just certain functions imported from your tools.js, then you can use a destructuring assignment which is supported in node.js since version 6.4 - see node.green.


Example: (both files are in the same folder)

tools.js

module.exports = {
    sum: function(a,b) {
        return a + b;
    },
    isEven: function(a) {
        return a % 2 == 0;
    }
};

main.js

const { isEven } = require('./tools.js');

console.log(isEven(10));

output: true


This also avoids that you assign those functions as properties of another object as its the case in the following (common) assignment:

const tools = require('./tools.js');

where you need to call tools.isEven(10).


NOTE:

Don't forget to prefix your file name with the correct path - even if both files are in the same folder, you need to prefix with ./

From Node.js docs:

Without a leading '/', './', or '../' to indicate a file, the module must either be a core module or is loaded from a node_modules folder.

Kristianmitk
  • 3,057
  • 4
  • 17
  • 38
10

You can put your functions in global variables, but it's better practice to just turn your tools script into a module. It's really not too hard – just attach your public API to the exports object. Take a look at Understanding Node.js' exports module for some more detail.

SeanRamzan
  • 96
  • 7
Jimmy
  • 31,408
  • 11
  • 74
  • 93
3

Include file and run it in given (non-global) context

fileToInclude.js

define({
    "data": "XYZ"
});

main.js

var fs = require("fs");
var vm = require("vm");

function include(path, context) {
    var code = fs.readFileSync(path, 'utf-8');
    vm.runInContext(code, vm.createContext(context));
}


// Include file

var customContext = {
    "define": function (data) {
        console.log(data);
    }
};
include('./fileToInclude.js', customContext);
user11153
  • 6,686
  • 4
  • 44
  • 45
1

This is the best way i have created so far.

var fs = require('fs'),
    includedFiles_ = {};

global.include = function (fileName) {
  var sys = require('sys');
  sys.puts('Loading file: ' + fileName);
  var ev = require(fileName);
  for (var prop in ev) {
    global[prop] = ev[prop];
  }
  includedFiles_[fileName] = true;
};

global.includeOnce = function (fileName) {
  if (!includedFiles_[fileName]) {
    include(fileName);
  }
};

global.includeFolderOnce = function (folder) {
  var file, fileName,
      sys = require('sys'),
      files = fs.readdirSync(folder);

  var getFileName = function(str) {
        var splited = str.split('.');
        splited.pop();
        return splited.join('.');
      },
      getExtension = function(str) {
        var splited = str.split('.');
        return splited[splited.length - 1];
      };

  for (var i = 0; i < files.length; i++) {
    file = files[i];
    if (getExtension(file) === 'js') {
      fileName = getFileName(file);
      try {
        includeOnce(folder + '/' + file);
      } catch (err) {
        // if (ext.vars) {
        //   console.log(ext.vars.dump(err));
        // } else {
        sys.puts(err);
        // }
      }
    }
  }
};

includeFolderOnce('./extensions');
includeOnce('./bin/Lara.js');

var lara = new Lara();

You still need to inform what you want to export

includeOnce('./bin/WebServer.js');

function Lara() {
  this.webServer = new WebServer();
  this.webServer.start();
}

Lara.prototype.webServer = null;

module.exports.Lara = Lara;
0

I was as well searching for an option to include code without writing modules, resp. use the same tested standalone sources from a different project for a Node.js service - and jmparattes answer did it for me.

The benefit is, you don't pollute the namespace, I don't have trouble with "use strict"; and it works well.

Here a full sample:

Script to load - /lib/foo.js

"use strict";

(function(){

    var Foo = function(e){
        this.foo = e;
    }

    Foo.prototype.x = 1;

    return Foo;

}())

SampleModule - index.js

"use strict";

const fs = require('fs');
const path = require('path');

var SampleModule = module.exports = {

    instAFoo: function(){
        var Foo = eval.apply(
            this, [fs.readFileSync(path.join(__dirname, '/lib/foo.js')).toString()]
        );
        var instance = new Foo('bar');
        console.log(instance.foo); // 'bar'
        console.log(instance.x); // '1'
    }

}

Hope this was helpfull somehow.

Community
  • 1
  • 1
zyexal
  • 1,510
  • 15
  • 23
0

Like you are having a file abc.txt and many more?

Create 2 files: fileread.js and fetchingfile.js, then in fileread.js write this code:

function fileread(filename) {
    var contents= fs.readFileSync(filename);
        return contents;
    }

    var fs = require("fs");  // file system

    //var data = fileread("abc.txt");
    module.exports.fileread = fileread;
    //data.say();
    //console.log(data.toString());
}

In fetchingfile.js write this code:

function myerror(){
    console.log("Hey need some help");
    console.log("type file=abc.txt");
}

var ags = require("minimist")(process.argv.slice(2), { string: "file" });
if(ags.help || !ags.file) {
    myerror();
    process.exit(1);
}
var hello = require("./fileread.js");
var data = hello.fileread(ags.file);  // importing module here 
console.log(data.toString());

Now, in a terminal: $ node fetchingfile.js --file=abc.txt

You are passing the file name as an argument, moreover include all files in readfile.js instead of passing it.

Thanks

Jeremy Wiebe
  • 3,769
  • 20
  • 31
Gajender Singh
  • 963
  • 9
  • 12
0

Another method when using node.js and express.js framework

var f1 = function(){
   console.log("f1");
}
var f2 = function(){
   console.log("f2");
}

module.exports = {
   f1 : f1,
   f2 : f2
}

store this in a js file named s and in the folder statics

Now to use the function

var s = require('../statics/s');
s.f1();
s.f2();
suku
  • 8,833
  • 13
  • 57
  • 108
0

You can simple just require('./filename').

Eg.

// file: index.js
var express = require('express');
var app = express();
var child = require('./child');
app.use('/child', child);
app.get('/', function (req, res) {
  res.send('parent');
});
app.listen(process.env.PORT, function () {
  console.log('Example app listening on port '+process.env.PORT+'!');
});
// file: child.js
var express = require('express'),
child = express.Router();
console.log('child');
child.get('/child', function(req, res){
  res.send('Child2');
});
child.get('/', function(req, res){
  res.send('Child');
});

module.exports = child;

Please note that:

  1. you can't listen PORT on the child file, only parent express module has PORT listener
  2. Child is using 'Router', not parent Express moudle.
Weijing Lin
  • 545
  • 2
  • 5
  • 15
-1

To turn "tools" into a module, I don't see hard at all. Despite all the other answers I would still recommend use of module.exports:

//util.js
module.exports = {
   myFunction: function () {
   // your logic in here
   let message = "I am message from myFunction";
   return message; 
  }
}

Now we need to assign this exports to global scope (in your app|index|server.js )

var util = require('./util');

Now you can refer and call function as:

//util.myFunction();
console.log(util.myFunction()); // prints in console :I am message from myFunction 
StefaDesign
  • 650
  • 6
  • 15
-2

To interactively test the module ./test.js in a Unix environment, something like this could be used:

    >> node -e "eval(''+require('fs').readFileSync('./test.js'))" -i
    ...
Dmitry S.
  • 1,165
  • 1
  • 8
  • 18
-4

Use:

var mymodule = require("./tools.js")

app.js:

module.exports.<your function> = function () {
    <what should the function do>
}
coder
  • 29
  • 7