第2章 Node.js入门

CommonJS模块

// Invoke 'strict' JavaScript mode
'use strict';

// Define a module variable
var message = 'Hello';

// Print message to the console
exports.sayHello = function() {
    console.log(message);
};

// Invoke 'strict' JavaScript mode
'use strict';

// Load the 'hello' module
var hello = require('./hello');

// Use the 'hello' module sayHello() method
hello.sayHello();

// Invoke 'strict' JavaScript mode
'use strict';

// Define the module method
module.exports = function() {
    // Define functional variable
    var message = 'Hello';

    // Print the message variable to the console
    console.log(message);
};

// Invoke 'strict' JavaScript mode
'use strict';

// Load the 'hello' module
var hello = require('./hello');

// Call the 'hello' module as a function
hello();

在加载模块时可以省略.js拓展名,Node会先寻找同名的文件夹,如果找不到,则寻找同名的js文件。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容