Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 850 Vote(s) - 3.52 Average
  • 1
  • 2
  • 3
  • 4
  • 5
In Node.js, how do I "include" functions from my other files?

#1
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.

Reply

#2
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.

Reply

#3
The vm module in Node.js provides the ability to execute JavaScript code within the current context (including global object). See

[To see links please register here]


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

[To see links please register here]


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);
}
Reply

#4
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;
Reply

#5
I was also looking for a NodeJS 'include' function and I checked the solution proposed by **Udo G** - see message

[To see links please register here]

. 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.

Reply

#6
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 ()
{
};
Reply

#7
## 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);
Reply

#8
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][1]. 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"](

[To see links please register here]

)) because functions and variables *defined* in the "imported" file [can't be accessed](

[To see links please register here]

) 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.

[1]:

[To see links please register here]

Reply

#9
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')()`
Reply

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

**main.js**


<!-- language: lang-js -->

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

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

//Passing Parameters
console.log("Sum of A and B = " + lib.add(20,30))
<!-- end snippet -->

**lib.js**


<!-- language: lang-js -->

this.ping=function ()
{
return "Ping Success"
}

<!-- end snippet -->


//Functions with parameters
this.add=function(a,b)
{
return a+b
}





Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through