Ok, i've tryed everything here. I did installed msnodesql from
-https://github.com/Azure/node-sqlserver
and
-http://www.microsoft.com/en-us/download/details.aspx?id=29995
following every line of instruction on installation. build with node-gyp... everything.
Then when I do something like:
var conn_str = "Driver={SQL Server Native Client 11.0};Server={(local)\\SQLEXPRESS};Database={DBName};Trusted_Connection={Yes};";
var stmt = sqlserver.query(conn_str, "SELECT * from av.CLIENT");
stmt.on('meta', function (meta) { console.log("We've received the metadata"); });
stmt.on('row', function (idx) { console.log("We've started receiving a row"); });
stmt.on('column', function (idx, data, more) { console.log(idx + ":" + data); });
stmt.on('done', function () { console.log("All done!"); });
stmt.on('error', function (err) { console.log("We had an error :-( " + err); });
it throws me an error on node console:
[Error: [msnodesql] Invalid passed to function query. Type should be .]
What drives me crazy is that it should be something like:
[Error: [msnodesql] Invalid --SOMETHING-- passed to function query. Type should be --SOMETHING_ELSE--.]
right?
It doesn't even pass through the stmt.on('error', line
I've repeated the installation steps over and over, thinking that maybe there was an error in the building process, but nothing.!
I'm using Windows 8 x64 and node v-0.10 (I wonder if that driver is ment to be use ONLY with node v.0.8 <
I need help. pls.
I have not used node-sqlserver, but I have used tedious and it worked well. Give that a try, maybe you'll have better luck?
Ok. I just found out why it gives errors like Error: [msnodesql] Invalid passed to function query. Type should be .] .
If you happen to have a prototype over the Array object, it will throw this kind of errors. For example, I have a prototype function over the Array class called "indexOfObject".....
To be more specific, there's a file in msnodesql > lib > sql.js , in it there's a function called validateParameters.
In there, I changed this:
if ( typeof parameters[p].value != parameters[p].type )
for this:
if ( typeof parameters[p].value != parameters[p].type && parameters[p].name )
it may not be overthinked as a solution to all my problems, but at least everything works fine from there on.!
Related
I'm create a website using ReactJS and I want get my local IP address. I've tried few ways to do that but I was confused with result.
First, I use module on npm is local-ip-url, then use localIpUrl() to get my ip address and display with console.log(). If i use a terminal to run this .js file (eg: node index.js), it print exact result i want (192.168.x.x). But if i use browser to see console log, it shows a different result 127.0.0.0.
I've tried another ways, create my own function:
const os = require('os');
function getAvailableIp() {
let ifaces = os.networkInterfaces();
let result = {};
for (let ifname in ifaces) {
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal !== false) return;
result[ifname] = iface.address;
});
};
return result;
}
function getIp() {
let ips = getAvailableIp();
return ips.WiFi || 'localhost';
}
Same like above, when I ran code in terminal, it showed perfect result. But on browser, function os.networkInterfaces() return a empty object {}(It has a property is proto, i think it doesn't cause problem). So, it always return localhost.
Anyone can explain?
I’ll start with the code:
var s = ["hi"];
console.log(s);
s[0] = "bye";
console.log(s);
Simple, right? In response to this, the Firefox console says:
[ "hi" ]
[ "bye" ]
Wonderful, but Chrome’s JavaScript console (7.0.517.41 beta) says:
[ "bye" ]
[ "bye" ]
Have I done something wrong, or is Chrome’s JavaScript console being exceptionally lazy about evaluating my array?
Thanks for the comment, tec. I was able to find an existing unconfirmed Webkit bug that explains this issue: https://bugs.webkit.org/show_bug.cgi?id=35801 (EDIT: now fixed!)
There appears to be some debate regarding just how much of a bug it is and whether it's fixable. It does seem like bad behavior to me. It was especially troubling to me because, in Chrome at least, it occurs when the code resides in scripts that are executed immediately (before the page is loaded), even when the console is open, whenever the page is refreshed. Calling console.log when the console is not yet active only results in a reference to the object being queued, not the output the console will contain. Therefore, the array (or any object), will not be evaluated until the console is ready. It really is a case of lazy evaluation.
However, there is a simple way to avoid this in your code:
var s = ["hi"];
console.log(s.toString());
s[0] = "bye";
console.log(s.toString());
By calling toString, you create a representation in memory that will not be altered by following statements, which the console will read when it is ready. The console output is slightly different from passing the object directly, but it seems acceptable:
hi
bye
From Eric's explanation, it is due to console.log() being queued up, and it prints a later value of the array (or object).
There can be 5 solutions:
1. arr.toString() // not well for [1,[2,3]] as it shows 1,2,3
2. arr.join() // same as above
3. arr.slice(0) // a new array is created, but if arr is [1, 2, arr2, 3]
// and arr2 changes, then later value might be shown
4. arr.concat() // a new array is created, but same issue as slice(0)
5. JSON.stringify(arr) // works well as it takes a snapshot of the whole array
// or object, and the format shows the exact structure
You can clone an array with Array#slice:
console.log(s); // ["bye"], i.e. incorrect
console.log(s.slice()); // ["hi"], i.e. correct
A function that you can use instead of console.log that doesn't have this problem is as follows:
console.logShallowCopy = function () {
function slicedIfArray(arg) {
return Array.isArray(arg) ? arg.slice() : arg;
}
var argsSnapshot = Array.prototype.map.call(arguments, slicedIfArray);
return console.log.apply(console, argsSnapshot);
};
For the case of objects, unfortunately, the best method appears to be to debug first with a non-WebKit browser, or to write a complicated function to clone. If you are only working with simple objects, where order of keys doesn't matter and there are no functions, you could always do:
console.logSanitizedCopy = function () {
var args = Array.prototype.slice.call(arguments);
var sanitizedArgs = JSON.parse(JSON.stringify(args));
return console.log.apply(console, sanitizedArgs);
};
All of these methods are obviously very slow, so even more so than with normal console.logs, you have to strip them off after you're done debugging.
This has been patched in Webkit, however when using the React framework this happens for me in some circumstances, if you have such problems just use as others suggest:
console.log(JSON.stringify(the_array));
Looks like Chrome is replacing in its "pre compile" phase any instance of "s" with pointer to the actual array.
One way around is by cloning the array, logging fresh copy instead:
var s = ["hi"];
console.log(CloneArray(s));
s[0] = "bye";
console.log(CloneArray(s));
function CloneArray(array)
{
var clone = new Array();
for (var i = 0; i < array.length; i++)
clone[clone.length] = array[i];
return clone;
}
the shortest solution so far is to use array or object spread syntax to get a clone of values to be preserved as in time of logging, ie:
console.log({...myObject});
console.log([...myArray]);
however be warned as it does a shallow copy, so any deep nested non-primitive values will not be cloned and thus shown in their modified state in the console
This is already answered, but I'll drop my answer anyway. I implemented a simple console wrapper which doesn't suffer from this issue. Requires jQuery.
It implements only log, warn and error methods, you will have to add some more in order for it to be interchangeable with a regular console.
var fixedConsole;
(function($) {
var _freezeOne = function(arg) {
if (typeof arg === 'object') {
return $.extend(true, {}, arg);
} else {
return arg;
}
};
var _freezeAll = function(args) {
var frozen = [];
for (var i=0; i<args.length; i++) {
frozen.push(_freezeOne(args[i]));
}
return frozen;
};
fixedConsole = {
log: function() { console.log.apply(console, _freezeAll(arguments)); },
warn: function() { console.warn.apply(console, _freezeAll(arguments)); },
error: function() { console.error.apply(console, _freezeAll(arguments)); }
};
})(jQuery);
I'm working on a script and I need to pass some arguments, the way I'm passing the arguments is like this:
xvfb-run casperjs --ignore-ssl-errors=true --ssl-protocol=any casper/server.js --checks='["215","216"]'
Inside the server.js I assign it to a variable:
var checks = casper.cli.get('checks');
Then below in the code I use the code in a loop:
casper.each(checks, function(check) {
$('*[data-queue="'+ check+'"] input:checkbox').prop('checked', false);
});
My issue is that although I do console.log(checks) to confirm that the arguments are being received the script keeps complaining with:
[error] [phantom] each() only works with arrays
Not only that but the loop doesn't work either if I hardcode the array manually.
casper.each callback takes TWO arguments, the first is the Casper module itself, the second is the iterated variable.
casper.each(checks, function(self, check) {
// ...
});
If you want to manipulate the HTML page then it has to be done in the page's context, inside of page.evaluate:
casper.each(checks, function(self, check) {
self.evaluate(function(check){
$('*[data-queue="'+ check+'"] input:checkbox').prop('checked', false);
}, check);
});
UPDATE
Sorry, didn't notice the CLI argument of --checks='["215","216"]'
Of course it's not an array:
console.log( checks );
console.log( typeof(checks) );
(notice the quotation marks ' ')
'[215,216]'
string
But if you use it like this: --checks=["215","216"]
and in the script:
console.log( typeof(eval(checks)) );
console.log( eval(checks)[1] );
object
216
(of cource eval is evil and all, so it's better to change format of incoming IDs)
casperjs casper/server.js --checks=215,216,15942,5435
console.log( typeof(checks.split(",")) );
console.log( JSON.stringify(checks.split(",")) );
object
["215","216","15942","5435"]
I want to get all names of files and directories from path and recognize them as files and directories. but When i run my code sometimes it works and somentimes it shows that directories are files. Here is the code
socket.on('data',function(path){
fs.readdir('path',function(err, data) {
var filestatus=[];
var z=0;
var i=data.length-1;
data.forEach(function(file){
fs.stat(file, function(err, stats) {
filestatus[z]=stats.isDirectory()
if (z==i){
socket.emit('backinfo',{names:data,status:filestatus});
}
z++;
})
})
})
})
During tests i realized that when i slow down data.forEach loop (using console.log(something) it works better(less miss). And this is strange.
This is about 96% incorrect, thank you to JohnnyHK for pointing out my mistake, see the comments below for the real problem / solution.
Because the fs.stat() function call is asynchronous, the operations on the filestatus array are overlapping. You should either use the async library as elmigranto suggested, or switch to using fs.statSync.
More details on what's happening:
When you call fs.stat(), it basically runs in the background and then immediately goes onto the next line of code. When it has got the details of the file, it then calls the callback function, which in your code is the function where you add the information to the filestatus array.
Because fs.stat() doesn't wait before returning, your program is going through the data array very quickly, and mutliple callbacks are being run simultanously and causing issues because the z variable isn't being incremented straight away, so
filestatus[z]=stats.isDirectory()
could be executed multiple times by different callbacks before z gets incremented.
Hope that makes sense!
you are using for statement in NODEJS and this will work if turned the For Statement to recursive function please see the attached code for help
function load_Files(pat,callback) {
console.log("Searching Path is: "+ph);
fs.readdir(pat,(err,files)=>
{
if(err)
{
callback(err);
}
else
{
var onlydir=[];
var onlyfiles=[];
var d=(index)=>
{
if (index==files.length)
{
console.log("last index: "+ index);
var ar=[];
ar.concat(onlydir,onlyfiles);
callback(null,ar);
return;
}
fs.stat(files[index],(err,status)=>
{
console.log("the needed file " +files[index]);
if (status.isDirectory())
{
onlydir.push(files[index]);
}
else
{
onlyfiles.push(files[index]);
}
console.log("only Directory: "+onlydir.length);
console.log("index: "+ index);
d(index+1);
}
)
}
d(0);
}
});
}
I have an Autocomplete working with geonames.org cities in the source: option and want to manipulate some of the arrays in the results. I have a "hard coded" test version running, but am having trouble manipulating the array variables to turn it into something useful.
A short statement of the problem is I can't get the alert statements to output readable strings. I get [object, Object] types of output. I need readable strings in the arrays for other code (not shown) to work. But other problems are: the Firebug Console output does not occur, and the Console gives me the following error statement - Error: Permission denied to access property 'item.autocomplete' - from line 2 of jQuery. This does not happen with the hard coded test. This is my first time using .grep and I'm not comfortable with .map, so I'm pretty sure the problems are array manipulations in those 3 sections.
Here's some relevant code. All the variables are declared, but I don't show all the declarations below.
citiesWithBoroughs = //a global array variable, populated in a prior select: option
source: function (request, response){
$.ajax({
success: function ( data ){
var geonamesResponse=$.map(data.geonames, function (item){
return {
label: item.name //and others
}
}
alert(citiesWithBoroughs + "," + citiesWithBoroughs.length + "|cWB2" ); //displays correct info
var noBoroughs=$.grep( geonamesResponse, function ( item, i ) {
for (var i=0; i < citiesWithBoroughs.length; i++ )
if( item.label === citiesWithBoroughs[i] ){ //compare geonamesResponse to each citiesWithBoroughs
console.log(citiesWithBoroughs[i]); //nothing in Console
return false; //drop any matches out of the geonamesResponse array
}
noBoroughs = $.map( data.geonames, function (item){ return item.label; });
console.log(noBoroughs); //nothing appears in Console
return true;
});
alert(noBoroughs.length + "," + citiesWithBoroughs.length + "," + geonamesResponse.length + "|3lengths" ); //correct info
alert(noBoroughs + "|nB" ); //in test, shows correct number of [object,Object] but no data
if( noBoroughs.length != geonamesResponse.length ){
var dropdownsCityWithBoroughs = $.grep( geonamesResponse, function ( item, i ) {
for (var i=0; i<citiesWithBoroughs.length; i++ )
if(item.label === citiesWithBoroughs[i]){return false;}
return true;
}, true )//true inverts grep to return the has-Boroughs city in the dropdown
alert(dropdownsCityWithBoroughs + "|dCWB"); //contains object, Object, but shows no data
}
}
}
}
I'm a novice so please give specific comments and code. I don't follow general instructions well.
The short statement of my problem was I could not read the output of my alerts, which contain arrays. Turns out JSON.stringify() fixes that. Other problems, like the Console.log statements not showing continue, but I can deal with that mysterious problem when the alerts work.