scribe js error - console.log not defined - javascript

I was using scribe js like
app.js
var scribe = require('scribe-js')();
var console=process.console;
app.use(scribe.express.logger());
app.use('/logs', scribe.webPanel());
and in my
module.js
var like = 0;
var error=require('./error');
var console=process.console; <-- this line
//only works if i comment above line
//else it shows console not defined
var like_dislike = {
like: function(req, res, next) {
like++;
console.log(process.console);
console.log("Like:" + like + " ClientTime:" + req.query.timestamp);
res.sendStatus(200)
}
}
module.exports=like_dislike
Any Idea, atleast where to start looking to resolve this ?
Thanks
EDIT
error.js
function error(res, custom_error, actual_error) {
if (actual_error)
console.error(actual_error);
res.status(custom_error.status).send(custom_error.text);
}
module.exports=error;

The problem is that the express router does not maintain a reference to the console variable (or process, it seems) while passing the request along to the handler. This problem persists even you you try to use the console variable inside an anonymous handler in the same file (not loading a submodule).
The solution is to cache a reference to Scribes console in app.locals and access it via req.app.locals.console. More details at this question: Global Variable in app.js accessible in routes?
I sent you a pull request on github. the updates that I have made are marked with comments in the style of:
/*
* update explination
*/

Related

Expressjs middleware keeps variable changed

I am trying to do a simple thing which is obvious I believe in the code below:
module.exports = function(req, res, next) {
var dop = require('../../config/config').DefaultOptions;
console.log(require('../../config/config').DefaultOptions);
console.log(dop);
dop.firstPage = 'test.sjs';
next();
};
This is an Expressjs middle ware which is very simple but the interesting point is that next time I load a page both of the console.log results has been changed to 'firstPage: test.sjs'. It shouldn't act like this and it should only change the dop variable.
Anyone with the knowledge why this creepy thing is happening?
Thank you
The main issue is require() is cached, so require('../../config/config') returns reference to the same instance, and as a result changing in one place causes all other references and subsequent requires to get that modified instance.
The simplest solution would be have a function in config to return a config object, that way every time invoking the get config function you will get a new instance with essentially the same content. I.e.:
config.js:
module.exports = {
getDefaultOptions: function(){
return {foo: 'bar', ip: '1.1.1.1'}
}
};

How to pass an image source in jade from a variable in node.js

This is my code from my index.js file (using express for routing)
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res){
var db = req.db;
var collection = db.get('usercollection');
var source = req.app.get('imgSource');
console.log("IMG SOURCE: " + source);
collection.find({},{},function(e,docs,source){
res.render('index',{
"userlist" : docs,
"imgURL" : source,
"title": "Insta-Famous"
});
});
});
module.exports = router;
And this is my code from my index.jade
extends layout
block content
h1= title
p Welcome to #{title}
ul
each user, i in userlist
li
p #{user.instaid}
p #{user.price}
li
img(src = "#{imgURL}")
source is a variable that is defined in app.js and then used in my index.js file. I know this variable has a value because it prints to console.log when I start my application. However the image does not load and instead displays a 404 question mark.
If I copy and paste the image source (which is: http://naccrra.org/sites/default/files/default_site_pages/2013/instagram-icon.png) then the image loads fine.
What am I doing wrong here?
Thank you in advance for your help.
You were accepting an argument with the same name that the varible from outer scope has and which you intended to use - source
var source = req.app.get('imgSource');
collection.find({},{},function(e,docs,source){
...
});
Any named argument to a function takes precedence over the same name variable of the outer scope. For example:
var a = 1;
var b = 2;
function fn(a){
a //=> 'precedence'
b //=> 2
}
fn('precedence');
If no variable was passed when calling, but the definition still takes a named argument, that argument will automatically be undefined, which is what was happening in your case. collection.find's callback is only ever called with two arguments - e and docs, any sunsequent arguments if named would have been set to undefined
You simply needed not take that extra named argument, which was unnecessary in the first place.
var source = req.app.get('imgSource');
collection.find({},{},function(e,docs){
...
});

Nodejs set command line argument as constant

I want to get an argv from my command line when I am going to start my server and then I want to set it as a constant for a module.
For example I want to define my log file path from commandline:
My starter.js looks like:
var optimist = require("optimist");
var server = require("./start_server");
var argv = optimist.describe('logpath', 'logptah for info').argv;
server.init({logpath:argv.logpath});
My start_server.js looks like:
var restify = require('restify');
var server = restify.createServer({
name: 'dummy-project'
});
module.exports.logpath = null;
function init(args){
server.listen(1234, function() {
console.log("inside logs");
console.log(args.logpath);
module.exports.logpath = args.logpath;
console.log('%s listening at %s', server.name, server.url);
});
};
module.exports.init = init;
var fun = require('./common/loghandler');
My loghandler.js looks like:
var server = require('./../start_server');
console.log("inside log handler");
var LOGPATH = server.logpath;
console.log(LOGPATH);
When I am running node starter.js --logpath='../../custom/info.txt'
I am not getting the logpath inside my loghandler.
Seems logpath handler is called before the server.listen.
The console output looks like:
node starter.js --logpath='../../custom/info.txt'
inside log handler
null
inside log handler
../../custom/info.txt
dummy-project listening at http://0.0.0.0:1234
How I can overcome it and pass my log path as command line argument?
Thanks in advance.
Your init() function is executed after starter.js uses require('./start_server'). When you use require(), the file and all its dependencies are loaded. That means during this process, you also executed require('./common/loghandler'), which completes before server.init() is run in starter.js. Since server.logpath hasn't been set by this time, you get a null value.
Aside from that, module.exports is set at require time and changing the values later have no effect. To fix the problems you're having, you should avoid using functions before your application has fully loaded, and put return values in your modules.

Javascript object member function referred to globally not recognized in callback

I'm having a problem with the following Javascript code (Phonegap in Eclipse):
function FileStore(onsuccess, onfail){
//chain of Phonegap File API handlers to get certain directories
function onGetSupportDirectorySuccess(dir){
//stuff
onsuccess();
}
function getDirectory(dir){
return "something" + dir;
}
}
var onFileStoreOpened = function(){
if (window.file_store instanceof FileStore){
console.log('window.file_store is a FileStore');
console.log(window.file_store.getDirectory('something'));
}
}
var onDeviceReady = function(){
window.file_store = new FileStore(onFileStoreOpened, onFileStoreFailure);
}
Here, I want to do some things to initialize file services for the app, and then use them in my initialization from the callback. I get the following error messages in LogCat:
07-03 06:26:54.942: D/CordovaLog(223): file:///android_asset/www/index.html: Line 40 : window.file_store is a FileStore
07-03 06:26:55.053: D/CordovaLog(223): file:///android_asset/www/cordova-1.8.1.js: Line 254 : Error in success callback: File7 = TypeError: Result of expression 'window.file_store.getDirectory' [undefined] is not a function.
After moving the code around and stripping out everything in getDirectory() to make sure it was valid, I'm not even sure I understand the error message, which suggested to me that getDirectory() is not seen as a member function of window.file_store, even though window.file_store is recognized as a FileStore object. That makes no sense to me, so I guess that interpretation is incorrect. Any enlightenment will be greatly appreciated.
I've since tried the following:
window.file_store = {
app_data_dir : null,
Init: function(onsuccess, onfail){
//chain of Phonegap File API handlers to get directories
function onGetSupportDirectorySuccess(dir){
window.file_store.app_data_dir = dir;
console.log("opened dir " + dir.name);
onsuccess();
}
},
GetDirectory : function(){
return window.file_store.app_data_dir; //simplified
}
}
var onFileStoreOpened = function(){
var docs = window.file_store.getDirectory();
console.log('APPDATA: ' + docs.fullPath);
}
var onDeviceReady = function() {
window.file_store.Init(onFileStoreOpened, onFileStoreFailure);
}
and I get
D/CordovaLog(224): file:///android_asset/www/base/device.js: Line 81 : opened dir AppData
D/CordovaLog(224): file:///android_asset/www/cordova-1.8.1.js: Line 254 : Error in success callback: File7 = TypeError: Result of expression 'docs' [null] is not an object.
All I want to do here is make sure certain directories exist (I've removed all but one) when I start, save the directory object for future use, and then retrieve and use it after all initialization is done, and I don't want everything in the global namespace. Of course I would like to be able to use specific instances when necessary, and I'm disturbed that I can't make it work that way since it demonstrates there is a problem with my understanding, but I can't even get this to work with a single, global one. Is this a Javascript problem or a Phonegap problem?
As it stands, your getDirectory function is a private function within FileStore. If you wanted to make it a 'member' or 'property' of FileStore, you would need to alter it a little within FileStore to make it like this:
this.getDirectory = function(dir){ };
or leave it how it is and then set a property....
this.getDirectory = getDirectory();
this way when new FileStore is called it will have getDirectory as a property because the 'this' keyword is always returned when calling a function with 'new'
Hope this quick answer helps. There's lots of stuff on the goog about constructor functions.
You understand it correctly. The getDirectory as it stands is a private function and cannot be called using the file_store instance.
Try this in the browser.
function FileStore(onsuccess, onfail){
function onGetSupportDirectorySuccess(dir){
//stuff
onsuccess();
}
this.getDirectory = function (dir){
return "something" + dir;
}
}
window.file_store = new FileStore('', ''); //the empty strings are just placeholders.
if (window.file_store instanceof FileStore){
console.log('window.file_store is a FileStore');
console.log(window.file_store.getDirectory('something'));
}
This will prove that the basic js code is working fine. If there still is a problem while using it in PhoneGap, comment.

Inheriting through Module.exports in node

This is probably me being stupid...
I'm using node with express and I have a seperate file using exports for routes. Above it, I require and cast to a variable, a package I have installed using npm.
var passwordHash = require('password-hash');
app.get("/signup", routes.signup);
inside routes.signup, I have:
passwordHash.generate(req.form.username, {algorithm: 'sha512'})
and it throwing an error saying passwordHash is undefined. How can I go about "inheriting" said require call?
You can also do the following (say this code is defined in app.js):
module.passwordHash = require('password-hash');
app.get("/signup", routes.signup);
in routes.signup:
var passwordHash = module.parent.passwordHash; // from app.js
passwordHash.generate(req.form.username, {algorithm: 'sha512'});
Separate files have separate scopes, so if you want to use passwordHash inside of your other file, then you need to call require('password-hash'); in that file too.
You can move your variables via app variable which should be accessible everywhere. Try to do something like that:
app.passwordHash = require('password-hash');
app.get("/signup", routes.signup);
The other thing that you might try is to use global variable, which means removing var from passwordHash. Not sure if this will work out for express, but it's worth checking.
passwordHash = require('password-hash');
app.get("/signup", routes.signup);
Let me know if it helped.
I know this question is old, but this would've helped me: Use exports!
So if I have a file called Index.js with this:
var model = require("./Model");
function test()
{
model.setMyVar("blah");
console.log(model.myVar);
}
My Model.js would look like this:
var myVar;
exports.myVar = myVar;
function setMyVar(value)
{
this.myVar = value;
}
exports.setMyVar = setMyVar;

Categories

Resources