Cloud foundry Error : Array.includes is not a function - node.js

I am trying to traverse through an array returned by fs library in my node.js application. In my local machine the following code is working fine:
var fs = require('fs');
var data = fs.readdirSync("<directory>");
if(data.includes('a')){
console.log('value found!');
}
But when I uploaded my same application in CloudFoundry, i got the error as:
Error: data.includes is not a function
can anyone explain what could be the reason for the same.

"Includes" doesn't work with Node 5.x So,please check node version.In order to make it work in current version.just follow below code.or you upgrade node to version 6.
if(data.indexOf('a')> -1){
console.log('value found!');
}

Related

Why JSZip can't create blob file?

I was trying JSZip on NodeJS to create some ZIP file but i'm facing an issue.
I'm using the code proposed by JSZip :
var JSZip = require('JSZip')
var zip = new JSZip()
zip.file("Hello.txt", "Hello World\n")
zip.generateAsync({type:"blob"}).then(function(content) {
//do things here
});
Currently the code throw an error on generateAsync
UnhandledPromiseRejectionWarning: Error: blob is not supported by this platform
Did something need to be install or the data I set in zip.file should be in a certain format ?
JSZip throws this error at jszip/lib/utils.js:352:15 because of the value of support.blob, defined by at jszip/lib/support.js (lines 11 to 32). I don't know for your machine, but while trying to run this script in NodeJS, I've debugged it to the conclusion that JSZip detects blobs to be not supported because self is not defined, so line 23 throws an error and support.blob is set to false.
JSZip seems to support the Node Buffer type on Node though - the following doesn't throw any errors on my machine:
// JSZip v3.2.1
// NodeJS v8.10.0
// Ubuntu 18.04
const JSZip = require('jszip');
const zip = new JSZip();
zip.file('hello.txt', 'Hello world\n');
zip
.generateAsync({type: 'nodebuffer'}) // blob -> nodebuffer
.then(console.log);

Module `fs` does not exist in the Haste module map

I'm new to Node.js and react-native. I followed the sample on send_telemetry.js exactly but when I run my react-native app I get an error: "The development server returned response error code 500.
the error message is:
bundling failed: Error: Unable to resolve module fs from ProjectPath\node_modules\azure-iot-device\lib\module_client.js: Module fs does not exist in the Haste module map";
Im running:
Node.js v10.15.3
NPM 6.4.1
react-native#0.59.2
First error was the same with Unable to resolve module events,
I can install events,
but the fs module is: "This package name is not currently in use, but was formerly occupied by another package. To avoid malicious use, npm is hanging on to the package name, but loosely, and we'll probably give it to you if you want it."
var Protocol = require('azure-iot-device-http').Http;
var DeviceClient = require('azure-iot-device').Client;
var Message = require('azure-iot-device').Message;
var connectionString = 'my connection string';
var client = DeviceClient.fromConnectionString(connectionString, Protocol);
function ConnectionTest(err) {
if (err) {
console.log('Could not connect: ' + err);
} else {
console.log('Client connected');
}
client.close(function () {
process.exit(0);
});
};
export async function Test() {
client.open(ConnectionTest);
};
Basically I need to know how to get the azure IOT hub client working in my react-native app (not using Expo).
Im pretty much stumped so any help would greatly be appreciated.
A dependency module is missing ... which is fs ...
this file-system npm module is incompatible with react-native ... cause it has it own different environment.
I had "import { symlink } from 'fs';" randomly pop up in one of my scripts. Once I deleted this line same issue you had went away. I would search your whole project for that line.

redis Error : ERR wrong number of arguments for 'set' command

i have an error with redis set command on local redis server(127.0.0.1:6379)
versions:
npm version : 2.15.0;
node version : 4.4.2;
nodejs verison : 0.10.25;
redis version : 2.7.1;
Error:
events.js:141 throw er; // Unhandled 'error' event
ReplyError: ERR wrong number of arguments for 'set' command at parseError
(/opt/xxx/xxx/node_modules/redis/node_modules/redis
parser/lib/parser.js:193:12) at parseType
(/opt/xxx/xxx/node_modules/redis/node_modules/redis-
parser/lib/parser.js:303:14)
all of my codes look like this:
redis.set("key","value")
on my local machine the code is running successfully , but on aws linux machine i got this error.
var matchedMaps = map.get(publicURIField);
if(matchedMaps) {
matchedMaps.forEach(function(matchedMap){
var patternToValidate = matchedMap.pattern;
var type = matchedMap.type;
var tagID = matchedMap.tagID;
var patternToCheck = "cs-uri-stem";
var patternToSave = "";
if(type==1){
patternToCheck = "c-referrer";
}
var regexToFind = new RegExp(patternToValidate.substring(1,patternToValidate.length-1));
var matchedPattern;
if (regexToFind.test(rawLogParsed[patternToCheck].toString())) {
if (matchedMap.regexType=="&"){
matchedMap.patterns.forEach(function(patternObject){
var key = patternObject.pattern.split("=")[0];
var value = rawLogParsed[patternToCheck].toString().split(key)[1];
if(rawLogParsed[patternToCheck].toString().split(key)[1].split("&")){
value = rawLogParsed[patternToCheck].toString().split(key)[1].split("&")[0];
}
patternToSave += key+value+"&";
});
}else{
matchedMap.patterns.forEach(function(patternObject){
if(patternObject.pattern.indexOf("*")>-1){
patternObject.pattern = patternObject.pattern.replace(/\*!/g, '.*');
}
patternToSave += rawLogParsed[patternToCheck].toString().match(patternObject.pattern)+"/";
});
}
patternToSave = patternToSave.substring(0,patternToSave.length-1);
var matchedField = publicURIField,matchedPattern = patternToSave
,key = tagID + "_"+userID+"_"+ matchedField + "_" + matchedPattern + "_" + type + "_" + fixedMinuteNumber;
if (tagUsageInfo[startKeyForRedis+key] == undefined) {
var tagObject = {
pattern:matchedPattern,
matchedField:matchedField,
userID:userID,
tagName:matchedMap.tagName,
monthNumber:parseInt(mMonthToCheck),
minuteNumber: parseInt(fixedMinuteNumber),
hourNumber: parseInt(yearMonthDayHourToCheck),
dayNumber: parseInt(yearMonthDayToCheck),
tagID: tagID,
matchedPattern: matchedPattern,
totalRequests: 1,
totalEgress: parseInt(bytes),
totalTransfered: parseInt(bytes),
totalRest: parseInt(totalWorld),
totalUS: parseInt(totalUS)
}
if(isIngress){
tagObject.totalIngres += parseInt(bytes);
}
dbclient1.set(startKeyForRedis+"tagUsage_"+key,JSON.stringify(tagObject));
tagUsageInfo[startKeyForRedis+"tagUsage_"+key] = startKeyForRedis+key;
}
else {
dbclient1.get(startKeyForRedis+"tagUsage_"+key, function(err, tagObject) {
var tagObjectJson = JSON.parse(tagObject);
tagObjectJson.totalRequests += 1;
tagObjectJson.totalEgress += parseInt(bytes);
tagObjectJson.totalTransfered += parseInt(bytes);
tagObjectJson.totalRest += parseInt(totalWorld);
tagObjectJson.totalUS += parseInt(totalUS);
tagObjectJson.totalRequests += 1;
if(isIngress){
tagObject.totalIngres += parseInt(bytes);
}
dbclient1.del(startKeyForRedis+"tagUsage_"+key);
dbclient1.set(startKeyForRedis+"tagUsage_"+key, JSON.stringify(tagObjectJson));
});
}
}
});
}
any help?
1)If your trying to run redis on windows set accepts only two arguments cause the redis version issue
2)try latest version of redis on linux it will work
Try installing this version of Redis on windows from the following link. You can find more information here https://github.com/ServiceStack/redis-windows
This link provides three options to install Redis on windows
Option 1) Install Redis on Ubuntu on Windows
Option 2) Running the latest version of Redis with Vagrant
Option 3) Running Microsoft's native port of Redis
I personally prefer option 3.
Hope this helped. Thanks.
all of my codes look like this: [...]
It's not important how all of your code looks like. It's important how the specific line that caused the problem looks like but unfortunately you didn't include it.
The errors that you provided include some files and line numbers but you seem to have removed the ones that are related to your code. If you read those messages carefully then you should be able to know what lines those errors are related to and focus on those lines.
If the errors show up on a server and not on your desktop then I would suspect that maybe you're trying to use some environment variables or files on the file system to populate some variables in your program, and those are not available on the server resulting in putting undefined there.
You will surely find the problem when you add console.log() statements to every place where you want to access Redis so that you first print it and then call to Redis. That way at least you will know what data is causing the problem. I suspect that you are having some undefined values or something like that.
Remember that JSON.stringify(undefined) returns undefined instead of a valid JSON string. Something like that may be causing problems. Adding debug messages will help to narrow it down.
Some extra advice: You can use prefix parameter of the redis module then you will not have to add startKeyForRedis+ all over the place. You can set a prefix once and have it prepended automatically. See the docs:
https://www.npmjs.com/package/redis
I was doing learning to use KUE a nodejs library for job scheduling that uses redis for saving data.
I got this error while running client.js(that puts jobs in queue) and worker.js(that process the schedule jobs).
I was running worker before running the client and that is why this happened.
I reversed the order and everything went fine!
To fix this error on windows Redis from v.3 required.
That's why I've took zipped release 3.0.504 from here and now all is working.
Quite simple.
I have faced similar type of error which was because of older version of Redis. This is compatibility issue which fixes a bug in Redis after Redis 2.6.12. Make sure you install recent version of Redis v3.X.

Script fails when using python-shell Node.js package

So I'm having a pretty odd issue. I have a python script whose function is to analyze an image and produce an output string. I decided to implement this script into the backend of my NodeJS server using the package 'python-shell.' The funny thing is, this script works perfectly when it's run on its own. It is able to analyze the image and produce the output string. However, when I attempt to have the 'python-shell' package run it, there is an error that is produced (related to the python code). I've tested and the python-shell runs the same version of python as is used at the terminal, so I'm not 100% sure why this issue is occurring. For reference, the below code is how I'm running the script:
var express = require('express');
var router = express.Router();
var pythonshell = require('python-shell');
pythonshell.defaultOptions = { scriptPath: '/path/to/myscript.py' };
var outputString = '';
var options = {args: ['-p', '/path/to/image.jpg']}
var pyshell = new pythonshell('myscript.py', options);
pyshell.on('message', function(message) {
// received a message sent from the Python script
console.log(message);
outputString = message;
});
pyshell.end(function(err) {
// This is where the error occurs
if (err) throw err;
console.log('Picture analysis complete');
console.log('outputString: ' + outputString);
});
Again, when the script is manually run (i.e. python myscript.py -p image.jpg), it runs perfectly fine. I can include the code in myscript.py, although I doubt that will help as it doesn't seem to be an error with the actual python code. The image is analyzed using several packages including OpenCV (and the produced error is, I believe, based off that). Any tips are greatly appreciated!
change the default path
pythonshell.defaultOptions = { scriptPath: '/path/to/myscript.py' };

module is not defined error

I am using nodejs in my meteor app and I added packages using mrt add npm and then in my client directory in packages.json I added skimlinksjs and its version and it is added to my app.
When I tried to using them in my app in server side code like this,
var res;
var skim = Meteor.require('skimlinksjs');
var apili = Meteor.require('/config.js');
skim.setup(apili.key);
skim.query({
searchFor: "title:\"moto g\"",
fq: "country:US"
}, function(err,data) {
res=data.skimlinksProductAPI.numFound;
}
);
return res;
and my config.js file is like this
module.exports = {
key: "xxxxxxx"
}
whenI'm running this application it is showing error like
module not defined
What went wrong with my code or is there any need to install other packages?
I just got the answer
Write this function in server side code
function returnAllResult()
{
var skimlinks = Meteor.require('skimlinksjs');
skimlinks.setup("xxx");
var skimlinks_query = Async.wrap(skimlinks.query);
var result = skimlinks_query({
searchFor: "title:\"moto g\"",
fq: "country:US",
rows:5
});
return result;
}
to know about asynchronous functions watch this
and then in my server side methods call this
apiresult:function()
{
var response = returnAllResult();
return response.skimlinksProductAPI.products[0].merchant;
}
that's it working fine now. Hope this helps someone

Resources