简体   繁体   English

Node.js 模块,function 没有正确导出

[英]Node.js Module, function isn't exporting properly

Trying to create utility functions, usually use python and getting used to node, this function won't export for some reason - says "SaveJson is not a function".尝试创建实用程序函数,通常使用 python 并习惯于节点,此 function 由于某种原因不会导出 - 说“SaveJson 不是函数”。

exports.mySaveJson = function(obj) {
    var blob,file,fileSets,obj;

      /**
     * Creates a file in the local drive
     */
    var date = new Date();
    var fs = require('fs');


     var n = date.toString();
     var name = n.concat("_scraped_data.json"); 
     //  console.log(name)


     fileSets = {
       name: name,
       mimeType: 'application/json'
     };



     blob = JSON.stringify(obj);
     file = fs.writeFile(fileSets, blob, callback);
return file;


   };

into进入

const SaveJson = require("./utilities.js")
....
SaveJson(ans)

Love some help just understanding what is wrong:)爱一些帮助只是了解什么是错的:)

I guess you should say SaveJson.mySaveJson(ans);我想你应该说SaveJson.mySaveJson(ans);

You are getting the module not the function.你得到的模块不是 function。 These are different things:这些是不同的东西:

const {mySaveJson} = require('./utitities.js');

and

const SaveJson = require('./utitities.js');

The First One extracts the exact function out of the module and sets it to the variable The First One从模块中提取确切的 function 并将其设置为变量

The Second One sets the whole module into the variable. The Second One将整个模块设置为变量。

Instead of calling:而不是调用:

const SaveJson = require("./utilities.js")
SaveJson(ans)

You need to call the actuall named function that you exported like:您需要调用您导出的名为 function 的实际名称:

const Util = require("./utilities.js")
Util.mySaveJson(ans);

Also, if you export multiple functions in utilities.js like:此外,如果您在utilities.js中导出多个函数,例如:

exports.mySaveJson = function(obj) {
   ...
}
exports.getJson = function() {
   ...
}

Then you can easily call this utility functions in any js file like:然后,您可以轻松地在任何 js 文件中调用此实用程序函数,例如:

const Util = require("./utilities.js")
...
Util.mySaveJson(ans);
const data = Util.getJson();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM