How to access the property of a function from module.exports - javascript

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.

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;

Related

Uncaught TypeError: x is not a function when Importing Factory Function

I have a factory function called updateUI which I am importing into index.js. When imported, the instance of updateUI is recognized, however I am given an error when attempting to call updateUI's methods.
Putting all of the code into index.js gets rid of the bug, but it still has me scratching my head. It seems the problem occurs only when importing. Why are the method's not being recognized?
index.js
import '../../dist/output.css';
import { updateUI } from './display.js';
const test = updateUI('Daly City');
test.setBackground();
display.js
import { getWeather } from './apiCall';
const updateUI = async(location) => {
const res = await getWeather(location, process.env.apiKEY);
function updateCity() {
const city = document.querySelector('#location');
city.innerHTML = res.name;
};
function updateCurrentTemp() {
const currentTemp = document.querySelector('#current-temp');
const farenheit = Math.round((9/5)*(res.main.temp - 273) + 32);
currentTemp.innerHTML = farenheit;
};
function updateConditions() {
const condition = document.querySelector('#weather');
condition.innerHTML = res.weather[0].description;
};
function setBackground() {
const date = new Date();
let time = date.getTime();
console.log(time);
};
return { updateCity, updateCurrentTemp, updateConditions, setBackground }
};
export { updateUI };
Question answered by #code in the comments.

Node.js: Exported function "is not a function" in one js file, but not another

So one of my files has a function that I need two of my other files to access. I am exporting this function with module.exports = {}. For some reason, one of my files is able to call this function, while I get a commands.commandRouter is not a function error when trying to call it from the other file. Here's basically what I've got going on:
commands.js
function commandRouter(commandName, commandType) {
if (commandType == 'sound') {
console.log(`${commandName} is a sound command, executing sound function`)
playAudio.playAudio(commandName.substring(1));
}
}
module.exports = {commandRouter}
main.js
const commands = require('./modules/commands.js');
const secondary = require('./modules/secondary.js');
client.on('message', (channel, tags, message, self) => {
if(message.charAt(0) == '!'){
console.log('Trigger character identified');
if(commands.commandList.hasOwnProperty(message.toLowerCase())) {
console.log('Valid command identified')
if (commands.commandList[`${message}`] == 'random' ) {
console.log('Random-type command identified')
secondary.randomSelectPropery(message.toLowerCase().substring(1));
}
else
{
console.log('Regular command identified')
commands.commandRouter(message, commands.commandList[`${message}`]);
}
}
}
}
commands.commandRouter(paramA, paramB); works just fine in this instance
secondary.js
const commands = require('./commands.js');
var randomSelectPropery = function (commandObject) {
randomObject = eval(commandObject);
var keys = Object.keys(randomObject);
console.log(randomObject)
console.log(`This object has ${keys.length} commands to choose from`);
var newCommandName = Object.getOwnPropertyNames(randomObject)[keys.length * Math.random() << 0];
console.log(newCommandName)
var newCommandType = randomObject[`${newCommandName}`]
console.log(newCommandType);
commands.commandRouter(newCommandName, newCommandType);
};
const perfect = {
"!perfectqube": "sound",
"!perfectsf2": "sound",
};
module.exports = { perfect, randomSelectPropery }
Here, commands.commandRouter(paramA, paramB); give the commands.commandRouter is not a function error.
File structure is as follows:
.\folder\main.js
.\folder\modules\commands.js
.\folder\modules\secondary.js

How to resolve the error TypeError: x is not a function for testing of the following function in Jest?

Function that I want to test
function setWebsite(website){
curWebsite = website;
var r = /:\/\/(.[^/]+)/;
myWebsite = website.replace(/^(https?:\/\/)?(www\.)?/,'');
return myWebsite;
}
code in test folder
const { setWebsite } = require('./popup');
test('should give current website name', () => {
const text = setWebsite('https://www.youtube.com/');
expect(text).toBe('youtube');
});
Error message
TypeError: setWebsite is not a function
In order to use a function in another file you need to export it:
function setWebsite(website) {
curWebsite = website;
var r = /:\/\/(.[^/]+)/;
myWebsite = website.replace(/^(https?:\/\/)?(www\.)?/, '');
return myWebsite;
}
module.exports.setWebsite = setWebsite;
And you are requiring a module not a function:
const popupModule = require('./popup');
test('should give current website name', () => {
const text = popupModule.setWebsite('https://www.youtube.com/');
expect(text).toBe('youtube');
});

combining knockout js with truffle app.js

I am learning on how to create a voting app with truffle and rendering on the screen everything goes well. So now I don't want to use vanilla js but want to add a framework to it, called knockout.js
I tried it in everyway but for some reason the knockout js is not working inside the app.js file given by truffle framework.
Here is the piece of code that works but it looks like the observables don't really work at all.
function AppViewModel() { // Loading the appviewmodel
var self = this;
App = {
web3Provider: null,
contracts: {},
account: '0x0',
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// TODO: refactor conditional
if (typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask.
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
web3 = new Web3(App.web3Provider);
}
return App.initContract();
},
initContract: function() {
$.getJSON("Election.json", function(election) {
// Instantiate a new truffle contract from the artifact
App.contracts.Election = TruffleContract(election);
// Connect provider to interact with contract
App.contracts.Election.setProvider(App.web3Provider);
return App.render();
});
},
render: function() {
var electionInstance;
var loader = $("#loader");
var content = $("#content");
var name = ko.observable('masnad'); //added the observable!
loader.show();
content.hide();
// Load account data
web3.eth.getCoinbase(function(err, account) {
if (err === null) {
App.account = account;
$("#accountAddress").html("Your Account: " + account);
}
});
// Load contract data
App.contracts.Election.deployed().then(function(instance) {
electionInstance = instance;
return electionInstance.candidatesCount();
}).then(function(candidatesCount) {
var candidatesResults = $("#candidatesResults");
candidatesResults.empty();
for (var i = 1; i <= candidatesCount; i++) {
electionInstance.candidates(i).then(function(candidate) {
console.log(candidate);
var id = candidate[0];
var name = candidate[1];
var voteCount = candidate[2];
// Render candidate Result
var candidateTemplate = "<tr><th>" + id + "</th><td>" + name + "</td><td>" + voteCount + "</td></tr>"
candidatesResults.append(candidateTemplate);
});
}
loader.hide();
content.show();
}).catch(function(error) {
console.warn(error);
});
}
};
}
$(document).ready(function () {
ko.applyBindings(new AppViewModel(), document.getElementById('vote_app'));
App.init();
});
I have attached comments on the above code where the knockout js observables are used but unfortunetly in the HTML file they don't exist.
Here is the piece of code on the HTML file that should work..
<h1 class="text-center"><span data-bind="text:name"></span></h1>
Knockout is not able to find the observable because you initialized it as a local variable, i.e., as var name = ...
Instead, you need to make it a property of the viewModel instance using the this operator, because that's how you expose it to the HTML.
Try replacing that line with
self.name = ko.observable('masnad');

Emitting custom event

I am using my custom yeoman generator programmatical in one of my nodejs module. I have written an Adapter to replace default TerminalAdapter.
The issues are,
When I am triggering custom event using emit method, I am not able
to listen for that event in my module. It is not getting fired.
Even end event listener also not getting fired.
Please let me know what I am missing here,
Below is my module code,
'use strict';
var fs = require('fs');
var path = require('path');
var MyOwnAdapter = require('./MyOwnAdapter');
var adapt = new MyOwnAdapter();
var env = require('./generator-myframewrk/node_modules/yeoman-generator')(null, {}, adapt);
env.register(path.resolve(__dirname, './generator-myframewrk'), 'myframewrk');
exports.run = function (options, answers) {
var obj = {};
adapt.setAnswers(answers);
process.chdir(options.projdir);
env.on("end", function(){
this.log("Even this is not getting called !!!"); //not coming here
}.bind(this));
env.on("alldone", function(){
this.log("Everything is done (including Bower install)"); //not coming here
obj.cb();
}.bind(this));
env.run('myframewrk', function(){
this.log('ran yo myframewrk, But bower install might be pending'); //coming here
});
return {
done: function (cb) {
obj.cb = cb;
}
};
};
Below is my Generator code,
var MyframewrkGenerator = yeoman.generators.Base.extend({
init: function () {
this.pkg = require('../package.json');
this.on('end', function () {
if (!this.options['skip-install']) {
this._installBower();
}
});
},
_installBower: function () {
this.log("Running bower install...");
/*reads bower.json and installs*/
bower.commands.install([], {}, {directory : "./"}).on('error', function (error) {
this.log("BOWER error::");
this.log(JSON.stringify(error));
}.bind(this)).on('log', function (log) {
this.log("BOWER LOG::"); // coming here
}.bind(this)).on('end', function (installed) {
this.log("BOWER END::"); // coming here
this.emit("alldone"); // my custom event
}.bind(this));
},
askFor: function () { ...
I took _installBower method out of this.on('end', function () {}); and made it a separate async func. This works fine. I don't need custom event anymore!
Thx...
bowerInstallHelper: function(){
if (!this.options['skip-install']) {
var cb = this.async();
this._installBower(cb);
}
}

Categories

Resources