I'm new to Node.js and I'm struggling to get a callback to work. I have the following function call:
memberPhotoPath(dbResults[i].userid2,dbResults[i].userid2Gender,'small',dbResults[i].userid2PhotoName,dbResults[i].userid2PhotoVerified,false,function(path) {
console.log(path);
});
and the following function:
function memberPhotoPath(userid,gender,photoSize,photoName,photoVerification,border,callback) {
if(photoVerification) {
callback('http://www.datingimages.co/online-dating/dating-photos/'+userid+'/'+userid+'-'+photoSize+'-'+photoName+'.jpg');
}else{
if(border) {
if(gender) {
callback('http://www.datingimages.co/online-dating/dating-website/default-female-image-'+photoSize+'.png');
}else{
callback('http://www.datingimages.co/online-dating/dating-website/default-male-image-'+photoSize+'.png');
}
}else{
if(gender) {
callback('http://www.datingimages.co/online-dating/dating-website/default-female-image-'+photoSize+'-noborder.png');
}else{
callback('http://www.datingimages.co/online-dating/dating-website/default-male-image-'+photoSize+'-noborder.png');
}
}
}
}
I get the following error in Node.js:
TypeError: undefined is not a function
at memberPhotoPath (/etc/node/index.js:315:5)
at /etc/node/index.js:223:21
at memberPhotoPath (/etc/node/index.js:315:5)
at /etc/node/index.js:214:9
at Array.forEach (native)
at /etc/node/index.js:208:34
at Query._callback (/etc/node/index.js:287:9)
at Query.Sequence.end (/usr/lib/node_modules/mysql/lib/protocol/sequences/Sequence.js:75:24)
at Query._handleFinalResultPacket (/usr/lib/node_modules/mysql/lib/protocol/sequences/Query.js:143:8)
at Query.EofPacket (/usr/lib/node_modules/mysql/lib/protocol/sequences/Query.js:127:8)
Any advice on what I'm doing wrong?
thankyou
I have just run this code in the chrome console and it works fine. The error must be somewhere down the line. With asynchronous functions it is sometimes not possible to track the exact stack trace. I advise you brace yourself and go through your other code again
Related
I'm using Node JS and ExpressJS to write my web server. I use JavaScript OOP fromfew time. I get an error running this class:
class myClass {
constructor(path) {
this.path = path;
}
myFunction(){
var fileControllerInstance = new FileController(this.path);
fileControllerInstance.fileExist(function(fileExist) {
if(fileExist){
console.log("file exist");
this.printLine("test");
}
else
return false;
});
}
printSTR(str){
console.log(str);
}
}
new myClass("filePath").myFunction();
module.exports = myClass;
Running this class I get an error on printSTR function. Error is the follow:
file exist
TypeError: Cannot read properties of undefined (reading 'printSTR')
Without this I get ReferenceError: printSTR is not defined. To solve my problem I need to create another class instance and to use that to call the function. Something like this:
new myClass("filePath").printSTR("test") instead to ``` this.printLine("test"); ```
Why using this my code not working? Thanks
Inside the function(fileExist), this has a different value than outside. To inherit the value inside, you must bind the function:
fileControllerInstance.fileExist(function(fileExist) {
...
}.bind(this));
You're calling this inside a callback. You can find this post useful to solve your issue.
Also you try to call printLine("test") but your method is printSTR(str)
In electron, I encounter the following error:
module.js:440
throw err;
^
Error: Cannot find module '../dialog'
at Module._resolveFilename (module.js:438:15)
at Function.Module._resolveFilename (/opt/App/resources/electron.asar/common/reset-search-paths.js:47:12)
at Function.Module._load (module.js:386:25)
at Module.require (module.js:466:17)
at require (internal/module.js:20:19)
at Object.get [as dialog] (/opt/App/resources/electron.asar/browser/api/exports/electron.js:35:14)
at process.<anonymous> (/opt/App/resources/electron.asar/browser/init.js:64:31)
at emitOne (events.js:96:13)
at process.emit (events.js:188:7)
at process._fatalException (node.js:276:26)
It happens on a child process spawn that fails in Linux. Strange because I do have a try catch block around that, yet it still results in an uncaughtexception, as seen in the code in browser/init.js from electron.asar:
// Don't quit on fatal error.
process.on('uncaughtException', function (error) {
// Do nothing if the user has a custom uncaught exception handler.
var dialog, message, ref, stack
if (process.listeners('uncaughtException').length > 1) {
return
}
// Show error in GUI.
dialog = require('electron').dialog
stack = (ref = error.stack) != null ? ref : error.name + ': ' + error.message
message = 'Uncaught Exception:\n' + stack
dialog.showErrorBox('A JavaScript error occurred in the main process', message)
}
As said, my code is in a try catch:
try {
server = childProcess.spawn(java, ["-jar", "App.jar"], {
"cwd": serverDirectory,
"detached": true
}, function(err) {
console.log("in callback");
});
} catch (err) {
console.log("here we are");
console.log(err);
}
But neither the callback nor the catch block is reached. Any ideas what is going on here and why the default dialog module cannot be found?
I found same error with electron 1.6.2
Figured it was due, when closing the application an error occur and electron want to display it in a dialog, maybe the close process has started and electron can't load this module, anyway I add:
const { dialog } = require('electron');
in main.js, no more error in console instead a dialog the error, I can fix it, After that I let the require just in case.
I hope I understand your question correctly...
If by "default dialog module", you mean the electron dialog API, then you can require that like so: const { dialog } = require('electron'). (Or in pre-1.0 versions simply require('dialog'). See https://github.com/electron/electron/blob/master/docs/api/dialog.md
Also the try/catch needs to be around the require in the child process. The try/catch you have is around the spawning of the child process in the parent. That require is failing in an entirely different node.js process, so it's not caught in the parent process that spawned it. It sounds like your child process code might work better if it looked like:
try {
const dialog = require('dialog');
} catch(e) {}
Also, if childProcess.spawn is referring to the core node module child_process, that doesn't accept a callback function. See https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options
Can you share the code from your child process? That might help more.
I am requiring a module and saving it in a variable. But when I call a module function by wrong name, it does not throw any error or consoles any error. How do I make this throw error?
var module = require('../pre_process/' + preProcessFolder + '/' + preProcessModule);
// module -> { XYZ: [Function] }
//Following does not throw error and doesn't console anything.How to handle/debug this error
module['XY'](result, userId)
.then(function(recData) {
})
I am using q library for promise.
So you want to check if a function (provided by a modul) exists.
You could use try like the example here:
Javascript check if function exists
I have my code:
this.Then(/^I should see "([^"]*)" link$/, function (callback) {
var logoutpath = by.xpath('//div[#id="account_logout"]/a');
browser.wait(function() {
return dv.isElementPresent(logoutpath);
}, 30000);
browser.driver.isElementPresent(logoutpath).then(function(isPresent){
expect(isPresent.isPresent()).toBe(true);
browser.driver.findElement(logoutpath).then(function(start){
start.click();
});
});
browser.sleep(2222);
console.log(">>>>>>>"+browser.getTitle());
callback();
});
when i run and get error in console:
TypeError: isPresent.isPresent is not a function
at c:\Users\binhlex\WebstormProjects\untitled\Feature\Steps\login_steps.js:33:30
at [object Object].promise.ControlFlow.runInFrame_ (c:/Users/binhlex/AppData/Roaming/npm/node_modules/protractor/node_modules/selenium-webdriver/lib/goog/../webdriver/promise.js:1857:20)
at [object Object].goog.defineClass.notify (c:/Users/binhlex/AppData/Roaming/npm/node_modules/protractor/node_modules/selenium-webdriver/lib/goog/../webdriver/promise.js:2448:25)
at [object Object].promise.Promise.notify_ (c:/Users/binhlex/AppData/Roaming/npm/node_modules/protractor/node_modules/selenium-webdriver/lib/goog/../webdriver/promise.js:564:12)
at Array.forEach (native)
I have some question?
- Why didn't i use isPresent method?
- When i run console.log(">>>>>>>"+browser.getTitle());, why it display >>>>>>>Promise::222 {[[PromiseStatus]]: "pending"}, how can i use it to verify with expected title of the page?
To your latest question, because browser.getTitle() is a promise, if you want to console.log Title you'd have to do: browser.getTitle().then(function(title){console.log(title)});
For your first question, I don't get why you are trying to obfuscate the code so much. in protractor you don't have to wait for element before clicking it. ( if you don't have ignore synchronization on).
So this:
browser.driver.findElement(logoutpath).then(function(start){
start.click();
equeals:
logoutpath.click()
The reason I ask, is because Node.js on ubuntu doesn't seem to have the fs.exists() function. Although I can call this when I run Node.js on my Mac, when I deploy to the server, it fails with an error saying the function does not exist.
Now, I am aware that some people consider it an "anti-pattern" to check if a file exists and then try and edit / open it etc, but in my case, I never delete these files, but I still need to check if they exist before writing to them.
So how can I check if the directory (or file) exists ?
EDIT:
This is the code I run in a file called 'temp.'s' :
var fs=require('fs');
fs.exists('./temp.js',function(exists){
if(exists){
console.log('yes');
}else{
console.log("no");
}
});
On my Mac, it works fine. On ubuntu I get the error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^ TypeError: Object #<Object> has no method 'exists'
at Object.<anonymous> (/home/banana/temp.js:2:4)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:32)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:41)
On my Mac - version : v0.13.0-pre
On Ubuntu - version : v0.6.12
It's probably due to the fact that in NodeJs 0.6 the exists() method was located in the path module: http://web.archive.org/web/20111230180637/http://nodejs.org/api/path.html – try-catch-finally
^^ That comment answers why it isn't there. I'll answer what you can do about it (besides not using ancient versions).
From the fs.exists() documentation:
In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.
You could do something like this:
fs.open('mypath','r',function(err,fd){
if (err && err.code=='ENOENT') { /* file doesn't exist */ }
});
The accepted answer does not take into account that the node fs module documentation recommends using fs.stat to replace fs.exists (see the documentation).
I ended up going with this:
function filePathExists(filePath) {
return new Promise((resolve, reject) => {
fs.stat(filePath, (err, stats) => {
if (err && err.code === 'ENOENT') {
return resolve(false);
} else if (err) {
return reject(err);
}
if (stats.isFile() || stats.isDirectory()) {
return resolve(true);
}
});
});
}
Note ES6 syntax + Promises - the sync version of this would be a bit simpler. Also my code also checks to see if there is a directory present in the path string and returns true if stat is happy with it - this may not be what everyone wants.
The Sync methods don't have any way of notifying about an error. Except for exceptions! As it turns out, the fs.statSync method throws an exception when the file or directory doesn't exist. Creating the sync version is as easy as that:
function checkDirectorySync(directory) {
try {
fs.statSync(directory);
} catch(e) {
try {
fs.mkdirSync(directory);
} catch(e) {
return e;
}
}
}
And that's it.
Using is as simple as before:
checkDirectorySync("./logs");
//directory created / exists, all good.
[]´z