0

I have the following code in my index.js

const test = require('./js/lerifier/start');
const $ = require("jquery");

$( document ).ready(function() {
  console.log( "ready!" );
  console.log(test.init());
});

I want to access the this.init() function from the lerifier function on start.js

const $ = require("jquery");
const SVGInjector = require('svg-injector');



module.exports = function Verifier() {


  this.init = function () {

    let mySVGsToInject = $('img.inject-me');

    let injectorOptions = {
        evalScripts: 'once',
        pngFallback: 'assets/png',
        each: function (svg) {
            // Callback after each SVG is injected
            console.log('SVG injected: ' + svg.getAttribute('id'));
        }
    };

    // Trigger the injection
    SVGInjector(mySVGsToInject, injectorOptions, function (totalSVGsInjected) {
        // Callback after all SVGs are injected
        console.log('We injected ' + totalSVGsInjected + ' SVG(s)!');
    });
  }
};

With the code stated in the index.js the error msg that I get is test.init is not a function, I know I'm doing something wrong or misunderstand the use of module.exports.

W9914420
  • 695
  • 2
  • 11
  • 25
  • 1
    You're exporting a function, so my guess is you need `test().init()` (and instead of "this is not working", state the exact error message you get) –  Jan 08 '18 at 20:40
  • don't you need to instantiate the Verifier object to be able to access its init method ? – Abderrahmane TAHRI JOUTI Jan 08 '18 at 20:40
  • Hi @ChrisG, yes I have updated my question, apologises i tried `test().init()` and I got an error msg that reads `cannont set property 'init' of undefined' – W9914420 Jan 09 '18 at 10:50
  • @AbderrahmaneTAHRIJOUTI, how would I do that in this instance? – W9914420 Jan 09 '18 at 10:50
  • 1
    @W9914420 `var inst = new test(); inst.init();` –  Jan 09 '18 at 10:57
  • @ChrisG this works for me, Would be best to provide this as an answer, incase someone like me falls into the same predicament. tnxs – W9914420 Jan 09 '18 at 11:04
  • This Q is essentially a duplicate of https://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it –  Jan 09 '18 at 13:13

1 Answers1

0

How about something like this. In this case there is a reference directly to the function in the start.js

 const test = require('./js/lerifier/start.js').Verifier;
Jason Allshorn
  • 1,625
  • 1
  • 18
  • 27