node.js模块导入导出_在Node JS中导出文件导入

node.js模块导入导出

This is a great asset of Node JS, which enables programmers to use a code file’s content in another code file. Also, it is just a matter of one or two commands that support reusability of code to a great extent.

这是Node JS的一项重要资产,它使程序员能够在另一个代码文件中使用一个代码文件的内容。 同样,仅需一个或两个命令就可以在很大程度上支持代码的可重用性。

For elaborating I have 4 code files:

为了详细说明,我有4个代码文件:

Code file 1:

代码文件1:

// this essentially will first run the whole code 
//of b then do the module export wala thing
var detail=require('./b');  

console.log(detail.info);

detail.info=5;

console.log(detail.info);

detail.print();

detail.printagain();

Code file 2:

代码文件2:

var z=1;

function hey(){
	console.log("hello ");
}

hey();

// module.exports.info=z;
// better way of doing this neeche hai !!!!
// module.exports.print=hey;

// 2nd method
module.exports={
	info:z ,
	print:hey ,
	printagain: function(){
		console.log("how r u ? ");
	},
	
	// object factory ,, each file importing this file 
	//can get individual copy of number
	object: function(){ 
		return {
			number:0
		}
	}
}


// this command cant run becoz printagain is 
// defined inside module.exports,, u can say this
// printagain();         
// is the disadvantage  2nd method

Code file 3:

代码文件3:

var coding=require('./b');

console.log(coding.info);

var object=coding.object();
console.log(object.number);

object.number=10;
console.log(object.number);

Code file 4:

代码文件4:

require('./a');

require('./c');

Output for code file 1

代码文件1的输出

Output 1

Output for code file 2

代码文件2的输出

Output 2

Output for code file 3

代码文件3的输出

Output 3

Output for code file 4

代码文件4的输出

Output 4

These code files are very comprehensive and easy to understand and all the fundamental concepts are covered in them. DON’T IGNORE COMMENTS IN CODE FILES. Major concepts are covered in it.

这些代码文件非常全面且易于理解,并且涵盖了所有基本概念。 不要忽略代码文件中的注释。 其中涵盖了主要概念。

Essentially it is important to note that for exporting variables and functions of a code file we need to use the module. Exports at the end of that code file and for importing a code file in another code file we need to use require followed by path for code file that is to be imported.

从本质上讲,重要的是要注意,要导出代码文件的变量和函数,我们需要使用模块。 在该代码文件的末尾导出,并在另一个代码文件中导入一个代码文件,我们需要使用require,然后是要导入的代码文件的路径。

翻译自: https://www.includehelp.com/node-js/export-import-of-files.aspx

node.js模块导入导出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值