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.
Create two js files
Main js file
Output
It worked with me like the following....
Lib1.js
now in the Main.js file you need to include Lib1.js
Please remember to put the Lib1.js in node_modules folder.
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
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 liketools.sum(1,2);
we can simply call
and then
in my case I have a file with controllers ctrls.js
and I can use
Categories
in every context as public class afterrequire('ctrls.js')()
You can require any js file, you just need to declare what you want to expose.
And in your app file:
Include file and run it in given (non-global) context
fileToInclude.js
main.js
Like you are having a file
abc.txt
and many more?Create 2 files:
fileread.js
andfetchingfile.js
, then infileread.js
write this code:In
fetchingfile.js
write this code: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