To include functions defined in another file in Node. js, we need to import the module. we will use the require keyword at the top of the file. The result of require is then stored in a variable which is used to invoke the functions using the dot notation.
You can simply do this:
user.js
class User {
//...
}
module.exports = User
server.js
const User = require('./user.js')
// Instantiate User:
let user = new User()
This is called CommonJS module.
Sometimes it could be useful to export more than one value. For example it could be classes, functions or constants. This is an alternative version of the same functionality:
user.js
class User {}
exports.User = User // 👈 Spot the difference
server.js
const {User} = require('./user.js') // 👈 Destructure on import
// Instantiate User:
let user = new User()
Since Node.js version 14 it's possible to use ES Modules with CommonJS. Read more about it in the ESM documentation.
⚠️ Don't use globals, it creates potential conflicts with the future code.
Using ES6, you can have user.js
:
export default class User {
constructor() {
...
}
}
And then use it in server.js
const User = require('./user.js').default;
const user = new User();
Modify your class definition to read like this:
exports.User = function (socket) {
...
};
Then rename the file to user.js
. Assuming it's in the root directory of your main script, you can include it like this:
var user = require('./user');
var someUser = new user.User();
That's the quick and dirty version. Read about CommonJS Modules if you'd like to learn more.
Another way in addition to the ones provided here for ES6
module.exports = class TEST{
constructor(size) {
this.map = new MAp();
this.size = size;
}
get(key) {
return this.map.get(key);
}
length() {
return this.map.size;
}
}
and include the same as
var TEST= require('./TEST');
var test = new TEST(1);
If you append this to user.js
:
exports.User = User;
then in server.js
you can do:
var userFile = require('./user.js');
var User = userFile.User;
http://nodejs.org/docs/v0.4.10/api/globals.html#require
Another way is:
global.User = User;
then this would be enough in server.js
:
require('./user.js');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With