I have two functions
myFuncs.js
function funcA(e){
console.log("FuncA:" + e);
}
function B(e){
console.log("FuncB:" + e);
}
I would like to make common.js style module for these.
However I have some basic question.
I have read some articles and try to understand standard method.
In this case,
I need to make two files separately for each function A and B?
Are these are correct??
in funcA.js
(function(definition){
funcA = definition();
})(function(){//
'use strict';
var funcA = function funcA(e){};
funcA.prototype = {
console.log("funcA"+ e);
}
return funcA;
});
in main.js
var funcA = require("funcA.js");
funcA.funcA("test");
You can put them in one module with
// myFuncs.js
exports.funcA = function(e){
console.log("FuncA:" + e);
}
// main.js
const myFuncs = require("./myFuncs")
myFuncs.funcA("test")
or export only one function
// funcA.js
module.exports = function(e){
console.log("FuncA:" + e);
}
// main.js
const funcA = require("./funcA")
funcA("test");
You need a relative path, because require("funcA") will look in node_modules. And module names are usually lowercase and dash separated.
Related
I have created a node module
Module file :
var functions = {};
functions.test = function(){
console.log("Invoked");
return "Hello";
}
module.exports = functions;
Main File :
const FUNCTIONS = require('./modulefile');
var x = FUNCTIONS.test();
console.log(x);
Now, here I can see "Invoked" means function is getting executed.
But x is undefined, seems value is not getting returned.
How can I return value from test() to main file.
You could use callbacks?
Hard to say what the underlying problem is considering people have got your code working.
Model file:
var functions = {
test: function(callback) {
console.log("Invoked");
callback("Hello")
}
}
module.exports = functions;
Other file:
var Functions= require('./functions');
var x
Functions.test(function (result) { x = result });
console.log(x);
Your code works just fine, I replicated it and it works
check it out here https://repl.it/#Muhand1/module-export
I've looked through a few questions related to this error, and most of them seem to be a misunderstanding of what the keyword this means. I don't think I'm having that problem here. Mine might be some sort of circular dependency problem that I cannot articulate well enough to figure it out on my own.
I've tried to distill my problem into three files presented below.
something.js
var A = require('../lib/a');
var Something = function (type) {
this.type = type;
};
Something.prototype.setTemplate = function (template) {
this.template = template;
};
Something.prototype.applyTemplate = function () {
var templateResult = this.template.calculate();
};
var factory = {};
factory.createSomething = function(type) {
return new Something(type);
};
factory.createA = function (input) {
return A.Make(input);
};
module.exports = factory;
a.js
var S = require('../prof/something');
var _ = require('underscore');
var A = function (input) {
this.input = input;
};
A.prototype.calculate = function () {
var calculation = 0;
var _s = S.createSomething('hello world');
// do calculation using input
return calculation;
};
var factory = {};
factory.Make = function (input) {
var a = new A(input);
return a;
};
module.exports = factory;
a_test.js
describe('Unit: A Test', function() {
var S = require('../prof/something');
it('test 1', function() {
var a = S.createA({
//input
});
var s = S.createSomething('type1');
s.setTemplate(a);
s.applyTemplate(); // error
});
});
The error gets thrown from the top level in a_test.js on the line with the comment //error. At the lowest level, the 'is not a function ' error is thrown in a.js at the S.createSomething(type) method. It says that S.createSomething() is not a function.
I've put a breakpoint in at that line and tried to call functions from the underscore library, but it gives the same error. So it seems that the require statements inside a.js are not throwing errors, but none of the injected objects can be used to call functions from. The a_test.js file is being run with the karma library.
Am I violating some javascript paradigm by referencing back and forth between A and S? How can I do this properly?
Edit: I've done some further testing. It doesn't actually matter if the test file looks like this:
describe('Unit: A Test', function() {
var S = require('../prof/something');
it('test 1', function() {
var a = S.createA({
//input
});
a.calculate(); // error
});
});
An error is still thrown at the line indicated above.
The files in the question reference each other. This is called cyclic dependencies. The solution is to move the var S = require('../prof/something'); statement into the calculate function like so:
a.js
// move the line from here
var _ = require('underscore');
var A = function (input) {
this.input = input;
};
A.prototype.calculate = function () {
var S = require('../prof/something'); // to here
var calculation = 0;
var _s = S.createSomething('hello world');
// do calculation using input
return calculation;
};
var factory = {};
factory.Make = function (input) {
var a = new A(input);
return a;
};
module.exports = factory;
I am new to JavaScript (working my way through some basic tutorials). Can someone tell me what I am doing wrong here? I am trying to get the run function to reference the withinCircle function, then export the whole thing to another file so I can reference the run function. Feel free to modify my code anyway you want- I tried to follow "best" practices but I may have screwed up. Thanks!
var roleGuard = {
/** #param {Creep} creep **/
run: function(creep)
{
var target = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {filter: { owner: { username: 'Invader' } }});
if(target!=null)
{
console.log(new RoomPosition(target.pos.x,target.pos.y,'sim'));
//ranged attack here
//within 3, but further than 1
if(creep.pos.getRangeTo(target)<=3&&creep.pos.getRangeTo(target)>1)
{
creep.rangedAttack(target);
console.log("ranged attacking");
}
}
else
{
var pp=withinCircle(creep,target,3,'sim');
console.log(pp);
creep.moveTo(pp);
}
}
//------------------------------------------------------------
//move to closest point within z units of given evenmy
withinCircle: function(creep,target,z,room)
{
var targets = [new RoomPosition(target.pos.x-z,target.pos.y-z,room), new RoomPosition(target.pos.x+z,target.pos.y-z,room),new RoomPosition(target.pos.x-z,target.pos.y+z,room),new RoomPosition(target.pos.x+z,target.pos.y+z,room)];
var closest = creep.pos.findClosestByRange(targets);
return(closest);
}
//------------------------------------------------------------
};
module.exports = roleGuard;
Other file contains:
var roleGuard = require('role.guard');
for example:
// foo.js
function add(a,b){
return a + b
}
module.exports = add
and in the other file:
// bar.js
const add = require("./foo");
console.log(add(1,1))
those paths are relative to the file location. extension can be omitted.
you'll need node or browserify or webpack to make exports/require to work properly.
if you want a better explanation about modular javascript, look there, even if you not enter in the browserify world it will present you to what we can do nowadays.
EDIT:
in order to export more symbols you can do the following:
// foo2.js
function add(a,b){
return a + b
}
function multiply(a,b){
return a * b
}
module.exports = {
add:add,
multiply:multiply
}
And then in the consumer:
// bar2.js
const add = require("./foo2").add
const multiply = require("./foo2").multiply
//...
This is also valid:
// foo3.js
function add(a,b){
return a + b
}
exports.add = add
function multiply(a,b){
return a * b
}
exports.multiply = multiply
Consumer will need no relevant alteration:
// bar3.js
const add = require("./foo3").add
const multiply = require("./foo3").multiply
//...
If using babel/es6 modules have a different idion, which you can check there.
Github source for reference
Files where issue exists: updateDB.js, quickstart.js
Inside quickstart.js I have set a variable updateDB on line 2:
var updateDB = require('./updateDB.js');
which I believe refers to my updateDB.js file (which is currently living in the same folder).
However later in the file when I try to call a function from updateDB.js on line 118:
updateDB.inputFormToDB(rows);
I get the error "updateDB.inputFormToDB is not a function".
Inside updateDB.js I have things set up as follows:
var updateDB= function() {
some function
var inputFormToDB = function(parameter) {
function code
}
some function
some function
};
module.exports = updateDB;
Am I missing something to call my function from inside quickstart.js??? I feel like I'm making some small mistake somewhere.
The problem is in
var updateDB = function() {...}
should be
var updateDB = {...}
like a Object.
e.g.
var updateDB = {
inputFormToDB: function() {...}
}
or
var updateDB = function() {
var x = ...
function inputFormToDB() {...}
return {
inputFormToDB: inputFormToDB
}
}
I want to organize my project imports with browserify so that I have a global utils variable from which I can call and execute functions much like jquery's $.
So in the end I want something like:
window.utils = ...
So I can use utils.aFunction();
I also want to divide my dependencies in several files, as an example, this would be my project:
libs
|_ math.js //Implements randomInt and RandomFloat methods
|_ connection.js //Implements isConnected method
utils.js //Calls all the required dependencies
My idea so far is to have something like this:
In libs/math.js:
module.exports = {
randInt: function() {
return 4;
},
randFloat: function() {
return 4.1;
}
};
And then I would do in utils.js:
var math = require('./libs/math');
var connection = require('./libs/connection');
var libs = [math, connection];
var utils = {};
for (var i = 0; i < libs.length; i++) {
for (var key in libs[i]) {
utils[key] = libs[i][key];
}
}
window.utils = utils;
This actually works just fine, but I don't know if it wasn't already solved by a library.
I have a feeling there are more efficient ways of doing this, what would be the recommended approach with browserify?
The code for throwing things into util object is definitely odd looking, and I wouldn't recommend this looping over all your required util submodules.
var libs = [math, connection];
var utils = {};
for (var i = 0; i < libs.length; i++) {
for (var key in libs[i]) {
utils[key] = libs[i][key];
}
}
If you were using a common js approach with webpack/browserify, you would simply declare your util to be global in the configuration file, and simply add the needed module.exports inside of your util.js
//connect.js
module.exports = {
isConnected: function(){
return true;
}
};
//math.js
module.exports = {
randInt: function() {
return 4;
},
randFloat: function() {
return 4.1;
}
};
//utils.js
exports.math = require('./math');
exports.connect = require('./connect');
//test.js
var utils = require('./utils');
console.log(utils.math.randInt());
console.log(utils.connect.isConnected());