[英]How to Export just a Function in NodeJS?
How to export only one function, except other functions and import it in other file.如何只导出一个函数,其他函数除外,并导入到其他文件中。
function messsageReceived(message) {
//print message
}
function readData(){
// reads data.
}
module.exports = mqtt_messsageReceived();
I want to use mqtt_messsageReceived in other file.我想在其他文件中使用mqtt_messsageReceived 。
To export just a single function from a module:要从模块中仅导出单个函数:
Module file:模块文件:
//function definition
function function_name(){...}
//Export
module.exports = function_name;
Import:进口:
const function_name = require('<relative path>/module_name');
//call imported function
function_name();
To export multiple functions:导出多个函数:
Module file:模块文件:
//function definitions
function function_name1(){...}
function function_name2(){...}
//Exports
module.exports.function_name1= function_name1;
module.exports.function_name2= function_name2;
Import:进口:
const module_name = require('<relative path>/module_name');// This returns module object with the functions from module's file.
//call imported function
module_name.function_name1();
module_name.function_name2();
What I did was declare a variable and store the functions there.我所做的是声明一个变量并将函数存储在那里。
var messages = {
getMessage : function(){
},
readData : function(){
}
}
module.exports = messages;
Then I called both functions from another file and both are working.然后我从另一个文件中调用了这两个函数,并且都在工作。
var message = require('./message');
message.getMessage();
message.readData();
I was getting confused because now the file where the functions are won't work if I directly do node message.js
.我很困惑,因为现在如果我直接执行node message.js
,函数所在的文件将无法工作。 I have to call them from another file from where I am importing them.我必须从导入它们的另一个文件中调用它们。
You can export function by Using Following Code :您可以使用以下代码导出功能:
var messsageReceived=function(message){
// your code here
}
module.exports = {
messsageReceived: messsageReceived
}
You can export only 1 function using the following ways您只能使用以下方式导出 1 个函数
1. 1.
module.exports = function messsageReceived(message) {
//print message
}
function readData() {
// reads data.
}
2. 2.
function messsageReceived(message) {
//print message
}
function readData() {
// reads data.
}
module.exports = messsageReceived;
you can do it in two way :你可以通过两种方式做到这一点:
module.exports = {
MyFunction(parameter){
console.log('export function');
}
};
Another one is :另一种是:
fuction MyFunction(){
console.log('export function');
}
module.exports.MyFuntion= Myfuction;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.