Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Node.js, how do I "include" functions from my other files?

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.

like image 740
TIMEX Avatar asked Apr 26 '11 23:04

TIMEX


People also ask

Can we call function from one js file to another?

As long as both are referenced by the web page, yes. You simply call the functions as if they are in the same JS file.

How do you call a function in NodeJS?

The call() method returns the result of calling the functionName() . By default, the this inside the function is set to the global object i.e., window in the web browsers and global in Node. js. Note that in the strict mode, the this inside the function is set to undefined instead of the global object.

Which function is used to include file modules in NodeJS?

Node js. Answer: require();


1 Answers

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 
like image 193
masylum Avatar answered Sep 21 '22 05:09

masylum