Home > Article > Web Front-end > What is CommonJS? How to customize modules in Nodejs?
JavaScript is a powerful object-oriented language with many fast and efficient interpreters. However, the JavaScript standard defines APIs for building browser-based applications. There is no standard library developed for a wider range of applications. The CommonJS specification was proposed mainly to make up for the shortcomings of the current JavaScript lack of standards. Its ultimate goal is to provide a standard library for languages similar to Python, Ruby and Java, rather than just staying at the stage of small script programs. Applications written with the CommonJS API can not only use JavaScript to develop client applications, but also write the following applications.
CommonJS is the standard for modularization, and nodejs is the implementation of CommonJS (modularization).
Node applications are composed of modules and adopt the CommonJS module specification.
One type is the module provided by Node, called the core module; the other type is the module written by the user, called the file module.
// 定义一个 tools.js 的模块 //模块定义 var tools = { sayHello: function() { return 'hello NodeJS'; }, add: function(x, y) { return x + y; } }; // 模块接口的暴露 // module.exports = tools; exports.sayHello = tools.sayHello; exports.add = tools.add; 1 2 3 4 var http = require('http'); // 引入自定义的 tools.js 模块 var tools= require('./tools'); tools.sayHello(); //使用模块
npm init --yes
[Recommended: node.js video tutorial】
The above is the detailed content of What is CommonJS? How to customize modules in Nodejs?. For more information, please follow other related articles on the PHP Chinese website!