如何从其他 Node.js 文件调用函数

5
这些代码存储在单独的文件中,我试图从该文件调用get方法到另一个nodejs文件,但我只得到[Function]作为输出。请问有人可以告诉我如何从这个文件调用get方法到另一个node js文件吗?
'use strict';
var createAPIRequest = require('../../lib/apirequest');
function Fitness(options) {
  var self = this;
  this._options = options || {};
  this.users = {
    dataSources: {
      get: function(params, callback) {
        var parameters = {
          options: {
            url: 'https://www.googleapis.com/fitness/v1/users/{userId}/dataSources/{dataSourceId}',
            method: 'GET'
          },
          params: params,
          requiredParams: ['userId', 'dataSourceId'],
          pathParams: ['dataSourceId', 'userId'],
          context: self
        };
        return createAPIRequest(parameters, callback);
      }     }   }; }

你是否发布了完整的文件? - bolav
请参考此链接:https://dev59.com/3m025IYBdhLWcg3wyZEn - RSKMR
4个回答

10
在这个文件中,您需要添加:

module.exports = Fitness

然后在您想要使用它的地方,您需要执行以下操作:

var Fitness = require('./fitness');


我遇到了一个错误(没有get方法),因为get方法在this.users = {dataSources: { get: function(params, callback) { }}}中。有什么解决方法吗? - VG__

3

我注意到的第一件事是"dataSources"属性在"users"对象内部。因此,你需要从外部访问这个对象,使用users.dataSources

为了使事情正常运行。

我已经在fitness.js中做出了一些更改

'use strict';
var createAPIRequest = require('../../lib/apirequest');

function Fitness(options) {
    var self = this;
    this._options = options || {};
    this.users = {
    dataSources  : { // You have property 'dataSources' in users object that will be accessible via Fitness object(Publically)
        get: function(params, callback) {
          var parameters = {
              options: {
                url: 'https://www.googleapis.com/fitness/v1/users/{userId}/dataSources/{dataSourceId}',
                method: 'GET'
              },
              params: params,
              requiredParams: ['userId', 'dataSourceId'],
              pathParams: ['dataSourceId', 'userId'],
              context: self
            };
            return createAPIRequest(parameters, callback);
         }    
       }   
    }; 
}

module.exports = Fitness; // This will export your Fitness constructor

现在,在另一个文件中访问Fitness模块,请编写以下代码。
var Fitness = require('pathToFitness/fitness.js');  // This will load your fitness module
var fitness = new Fitness(options); // Create object of class Fitness
fitness.users.dataSources.get();  // Access get() method 

我尝试了另一种方式:(module.exports = google) 这个google包含了所有的谷歌API,包括上面提到的nodejs中的fitness API。当从另一个文件访问google时,它返回的输出为"fitness:[Function]"。那么在这种情况下,如何才能从google中访问fitness的get方法呢?是否可能实现?如果我像这样尝试'google.fitness',它会返回'Function',而在'google.fitness.users'的情况下,它会返回'undefined'。有人可以帮我知道解决方案吗?(例如调用google,google调用fitness,fitness有get方法) - VG__

2

get是一个内部函数,需要创建类。在您的模块中,您可以导出整个类:

module.exports.Fitness = Fitness;

在你的其他模块中:

var f = require('./Fitness'); /* given that Fitness.js is the name */
var fitness = new f.Fitness(...); /* call module.exports.Fitness of required file */
fitness.users.dataSources.get(...);

您尝试过这样吗?如果是的话,您在哪里遇到了错误?

1
太好了,谢谢 - 今晚第一次学习Node,这篇文章帮了我很大的忙。 - RichAppz

0
    * just make 2 file one will have file read operation and another will fetch data
 Hi like you are having a file abc.txt and many more 
    create 2 file   ||  fileread.js and  fetchingfile.js
    **in fileread.js  write this code***




         function fileread(filename){

            var contents= fs.readFileSync(filename);
            return contents;
            }

            var fs =require("fs");  // file system

            //var data= fileread("abc.txt");
            module.exports.fileread =fileread;
            //data.say();
            //console.log(data.toString());


        **in fetchingfile.js  write this code**

            function myerror(){

                console.log("Hey need some help");
                console.log("type file=abc.txt");
            }

            var ags = require("minimist")(process.argv.slice(2),{string: "file" });
            if(ags.help || !ags.file) {

                myerror();
                process.exit(1);
            }
            var hello=require("./fileread.js");
            var data= hello.fileread(ags.file);  // importing module here 
            console.log(data.toString());

    **in your cmd type 
    node fetchingfile.js --file=abc.txt** 



    you are passing file name as a argument moreover include all file in readfile.js instant of passing it 
    thanks 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接