I have the following two files in a folder:
plus one file in same folder called minions_model
But when i try to call murder_model with:
var murder_model = require('./murder_model.js');
and call it to see its functions, i get:
{}
while i should see something like:
{ xxx: [Function: xxx] }
Update:
It seems like missionModel fails to get murder file because of minionModel.
I noticed if i removed minionModel reference from Murder file, it would work.
But minionModel crashes because of Mission_model. so if i remove minionModel from MissionModel it would work. But its an infinity Loop!.
What causes this and how can i fix it?
Source:
minions:
var path = require('path');
var missionsCompålicated = require('./mission_model.js');
var mongoose = require('mongoose');
function yyy() {
console.log("inside minions");
return 499;
}
module.exports = {
yyy : yyy,
};
Murder:
var path = require('path');
var MinionModel = require('./minions_model.js');
function xxx() {
console.log("inside murder model");
}
module.exports = {
/*botAttack : botAttack,*/
xxx : xxx,
};
mission:
var xau = require('./murder_model.js');
function getMission(userid) {
console.log("??:)");
console.log(xau);
console.log(xau.xxx());
}
module.exports = {
getMission : getMission,
};
Its weird, because if i call it anywhere else ( not in minion,murder or mission, for example server.js it works perfectly.
This happens because you are replacing the entire module.exports object and the two modules are requiring each other and causing a cyclic dependency. You can solve it my not replacing the module.exports object.
Try this :
module.exports.getMission = getMission;
module.exports.xxx = xxx;
module.exports.yyy = yyy;
i want to access a model name userRegistration in my custom js file but every time its showing undefined and shows this error
TypeError: Cannot call method 'findOne' of undefined
please Check code
var loopback = require('loopback');
var app = loopback();
var nodemailer = require("nodemailer");
var smtpTransport = require("nodemailer-smtp-transport");
var path=require('path');
var fs=require('fs');
var Handlebars = require('handlebars');
exports.mailToUser=function(req,res,next){
var userNotification = app.models.UserNotification;
var userregister = app.models.UserRegistration;
userregister.findOne({where:{email:email}},function(err,userobj){
if(err){
next()
}
})
}
Thanks
You shouldn't use var app = loopback();
If you want to access to app you can require your server.js or some other ways existed. The simple one is requiring server
I have this opcode.js file and need to test it with mocha.An example can be seen here :
var opcode = {
'0': {
decode: function (data) {
var ocBuf = new OpcodeBuffer(data);
var kpo = {};
kpo.opcode = 0x00;
ocBuf.setIndex(1);
kpo.sid = ocBuf.readUInt16();
return kpo;
},
encode: function (kpo) {
var ocBuf = new OpcodeBuffer(opcode['0'].encodeLength(kpo));
ocBuf.writeUInt8(0x00);
ocBuf.writeUInt16(kpo.sid);
return ocBuf.buf;
}
module.exports = opcode;
and the write in my test_ack.js file:
var op = require('./ack.js');
var assert = require('assert');
opcode = op.opcode;
var decode = require('opcode').decode();
var encode = require('opcode').encode();
the problem is that i keep having this encode and decode not defined error messages.I still cannot get how can i import them in my directory.
Given the code you show us, this would be the way you could import your two functions:
var decode = require('opcode')["0"].decode;
var encode = require('opcode')["0"].encode;
I'd suggest additionally avoiding calling require twice. Among other things, the code you currently have calls the functions instead of just importing them.
I am new to node.js and trying to create my first module.
But i am getting an error
TypeError: Object function SetAstAppLog.....has no method 'on'
My module file contains following code :
var EventEmitter = require('events').EventEmitter;
var util = require('util');
module.exports = SetAstAppLog;
util.inherits(SetAstAppLog, EventEmitter);
function SetAstAppLog(logFolderPath,fileNamePrefix,fileSize,logStreamObject) {
EventEmitter.call(this);
.
.
.
.
this.emit('objCreated');
}
and in app.js i am doing following things :
var SetAstAppLog = require('astAppLog');
var fileSize = 1024;
SetAstAppLog.on('objCreated', function () {
console.log('an object was created');
});
SetAstAppLog.on('written', function () {
console.log('Write operation completed.');
});
var objCommLogger = new SetAstAppLog(logFolderPath,logCommFilePrefix,fileSize,logCommMsg);
var objErrorLogger = new SetAstAppLog(logFolderPath,logErrorFilePrefix,fileSize,logErrorMsg);
Here, i am using node js with v0.10.21.
I am not able to find out why i am getting this error even my module file contains EventEmitter
Can anyone help to solve this issue?
You are exporting the function without calling it. You need to call it:
var SetAstAppLog = require('astAppLog')();
Edit: I failed to notice that you called the function lower in your script. You should be attaching the event handlers to the instances, not the constructor.
var objCommLogger = new SetAstAppLog(logFolderPath, logCommFilePrefix, fileSize, logCommMsg);
objCommLogger.on(...);
Essentially what I need to do is to take a local grader.js file and then use it at the command line to input HTML, which will then output JSON data to the console to validate the existence of several HTML elements. The usage looks something like this:
./grader.js --checks checks.json --file index.html
./grader.js --checks checks.json --url http://google.com
The Node modules being used are Commander (for working at the command line), Cheerio (for HTML), and Restler (for getting HTML from URL).
The checks.json file is straightforward in that it's simply asking to check for the existence of a few simple HTML elements to find out whether or not they exist on the page:
["h1",
".navigation",
".logo",
".blank",
".about",
".heading",
".subheading",
".pitch",
".video",
".thermometer",
".order",
".social",
".section1",
".section2",
".faq",
".footer"]
The grader.js file is where things get a little more complicated. The following code actually works insofar as it takes the command line arguments and does indicate a true or false value as to whether the HTML elements exist. But it doesn't work properly after adding the URL check at the bottom. There is something wrong with my checkURL function and the way that I implement it using the Commander code at the bottom. Even though the true and false values are correct dependent upon the HTML file/URL I use, I end up spitting out both checks to the console even if I only want to check either the file or the URL, not both. I'm fairly new to this so I'm surprised that it works at all. It may have something to do with the default values, but when I try to make those changes the checkURL function seems to break down. Thanks in advance for your help I really do appreciate it.
#!/usr/bin/env node
var fs = require('fs');
var program = require('commander');
var cheerio = require('cheerio');
var rest = require('restler');
var HTMLFILE_DEFAULT = "index.html";
var CHECKSFILE_DEFAULT = "checks.json";
var URL_DEFAULT = "http://cryptic-spire-7925.herokuapp.com/index.html";
var assertFileExists = function(infile) {
var instr = infile.toString();
if(!fs.existsSync(instr)) {
console.log("%s does not exist. Exiting.", instr);
process.exit(1); // http://nodejs.org/api/process.html#process_process_exit_code
}
return instr;
};
var cheerioHtmlFile = function(htmlfile) {
return cheerio.load(fs.readFileSync(htmlfile));
};
var loadChecks = function(checksfile) {
return JSON.parse(fs.readFileSync(checksfile));
};
var checkHtmlFile = function(htmlfile, checksfile) {
$ = cheerioHtmlFile(htmlfile);
var checks = loadChecks(checksfile).sort();
var out = {};
for(var ii in checks) {
var present = $(checks[ii]).length > 0;
out[checks[ii]] = present;
}
return out;
};
var checkUrl = function(url, checksfile) {
rest.get(url).on('complete', function(data) {
$ = cheerio.load(data);
var checks = loadChecks(checksfile).sort();
var out = {};
for(var ii in checks) {
var present = $(checks[ii]).length > 0;
out[checks[ii]] = present;
}
console.log(out);
});
}
var clone = function(fn) {
// Workaround for commander.js issue.
// http://stackoverflow.com/a/6772648
return fn.bind({});
};
if(require.main == module) {
program
.option('-f, --file <html_file>', 'Path to index.html', clone(assertFileExists), HTMLFILE_DEFAULT)
.option('-u, --url <url>', 'URL to index.html', URL_DEFAULT)
.option('-c, --checks <check_file>', 'Path to checks.json', clone(assertFileExists), CHECKSFILE_DEFAULT)
.parse(process.argv);
var checkJson = checkHtmlFile(program.file, program.checks);
var outJson = JSON.stringify(checkJson, null, 4);
console.log(outJson);
var checkJson2 = checkUrl(program.url, program.checks);
var outJson2 = JSON.stringify(checkJson2, null, 4);
console.log(outJson2);
}
else {
exports.checkHtmlFile = checkHtmlFile;
}
Depending on the arguments call either one of checkHtmlFile() or checkUrl()
Something like:
if (program.url)
checkUrl(program.url, program.checks);
else checkHtmlFile(program.file, program.checks);
Read this for more references: commander.js option parsing
Also, checkJson2 is undefined as checkUrl() isn't returning anything.
Those commander .option lines look wrong to me.
Delete the clone function and revise your option lines as follows:
.option('-f, --file <html_file>', 'Path to index.html', HTMLFILE_DEFAULT)
.option('-u, --url <url>', 'URL to index.html', URL_DEFAULT)
.option('-c, --checks <check_file>', 'Path to checks.json', CHECKSFILE_DEFAULT)
This should solve your commander problem.
Here is the updated checkUrl function after the helpful hints from #David and #ankitsabharwal.
var checkUrl = function(url, checksfile) {
rest.get(url).on('complete', function(data) {
$ = cheerio.load(data);
var checks = loadChecks(checksfile).sort();
var out = {};
for(var ii in checks) {
var present = $(checks[ii]).length > 0;
out[checks[ii]] = present;
}
var outJson = JSON.stringify(out, null, 4);
console.log(outJson);
});
}
And here is the updated Commander code below:
if(require.main == module) {
program
.option('-f, --file <html_file>', 'Path to index.html')
.option('-u, --url <url>', 'URL to index.html')
.option('-c, --checks <check_file>', 'Path to checks.json')
.parse(process.argv);
if (program.url) {
checkUrl(program.url, program.checks);
} else {
checkHtmlFile (program.file, program.checks);
var checkJson = checkHtmlFile(program.file, program.checks);
var outJson = JSON.stringify(checkJson, null, 4);
console.log(outJson);
}
}