简体   繁体   中英

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".

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);

You are getting the module not the 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 Second One sets the whole module into the variable.

Instead of calling:

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

You need to call the actuall named function that you exported like:

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

Also, if you export multiple functions in utilities.js like:

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

Then you can easily call this utility functions in any js file like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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