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.
This is the best way i have created so far.
You still need to inform what you want to export
app.js
tools.js
If you'd like to take advantage of multiple CPUs & Microservice architecture, to speed things up...Use RPCs over forked processes.
Sounds complex, but it's simple if you use octopus.
Here's an example:
on tools.js add :
on app.js, add :
disclosure - I am the author of octopus, and built if for a similar usecase of mine, since i couldn't find any lightweight libraries.
You can simple just
require('./filename')
.Eg.
Please note that:
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)
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: