本文主要是介绍NodeJs(三)CommonJs模块,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1新建libs.js
exports.hello='world';
exports.add = function(a,b){
return a+b;}
exports.gbg = {
hello:'world'}
module.exports = function minus(a,b){
return a-b;
}
setTimeout(() => {
console.log(exports);
console.log(module.exports);
}, 2000);
2新建index.js
console.log('start require')
var lib = require('./lib.js') // commonJs规范
console.log('end require',lib);
lib.additional = 'test';
实战:
游戏主程序index.js
var game = require('./lib');
let count = 0;
process.stdin.on('data',e=>{
const playAction =e.toString().trim();
const result = game(playAction);
if(result ==-1){
count++;
}
if(count===3){
console.log('你厉害了,我不玩了!');
process.exit();
}
})
模块加载程序:lib.js
module.exports = function(playAction){
var random =Math.random()*3;
if(random<1){
var computerAction ='rock'
}else if(random>2){
var computerAction ='scissor'
}else{
var computerAction ='paper'
}
console.log("电脑"+computerAction);
if(computerAction==playAction){
console.log('平局');
return 0;
}else if(
(computerAction=='rock'&&playAction=='paper')||
(computerAction=='scissor'&&playAction=='rock')||
(computerAction=='paper'&&playAction=='scissor')
){
console.log('你赢了');
return -1;
}else{
console.log("你输了");
return 1;
}
}
这篇关于NodeJs(三)CommonJs模块的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!