Encapsulation is one of the main principles of object-oriented programming. It allows an object to separate its interface from its implementation, meaning the data and the methods (or functions) that manipulate that data are bundled together.
In Node.js, you can create data encapsulation through different methods, like using classes, closures, and modules.
1. Using Classes:
You can create a class in Node.js using the `class` keyword. Here’s a simple example:
```
class User {
constructor(name, age){
this.name = name;
this.age = age;
}
let user1 = new User(“John”, 22);
console.log(user1.getName()); // John
console.log(user1.getAge()); // 22
```
In this example, `name` and `age` are encapsulated in `User` class, and they’re only accessible through the methods `getName` and `getAge`.
1. Using Closure:
A closure is a function that has access to its own scope, the outer function’s scope, and the global scope. We can create private variables/functions using closures that can provide data encapsulation.
```
function User(name, age) {
this.getName = function() {
return name;
}
let user1 = new User(‘John’, 22);
console.log(user1.getName()); // John
console.log(user1.getAge()); // 22
```
1. Using Module:
In Node.js, modules are also used to encapsulate data. Each module has its own context, so it cannot interfere with other modules. You can export from a module to make them accessible to other modules.
Here’s an example:
user.js:
```
let name = “John”;
let age = 22;
function getName() {
return name;
}
function getAge() {
return age;
}
module.exports = { getName, getAge };
```
app.js:
```
let user = require(‘./user.js’);
console.log(user.getName()); //John
console.log(user.getAge()); //22
```
In this example, `name` and `age` are encapsulated in the `user` module.