nodejs cookie-session typeerror - node.js

TypeError: this.keys.index is not a function
the console log show that the if condition line is error
app.get('/',(req,res)=>{
if(!req.session.authenticated){
res.redirect('/login');
}else{
res.redirect('/search')
}
})
it was fine until i start another server.js from a completely different folder. I have tried to reinstall the node_module to fix it but it just result the same. but the weird part is i can start the server in a vm without any problem. can any help me with this?
Cookies.prototype.get = function(name, opts) {
var sigName = name + ".sig"
, header, match, value, remote, data, index
, signed = opts && opts.signed !== undefined ? opts.signed : !!this.keys
header = this.request.headers["cookie"]
if (!header) return
match = header.match(getPattern(name))
if (!match) return
value = match[1]
if (!opts || !signed) return value
remote = this.get(sigName)
if (!remote) return
data = name + "=" + value
if (!this.keys) throw new Error('.keys required for signed cookies');
index = this.keys.index(data, remote)
if (index < 0) {
this.set(sigName, null, {path: "/", signed: false })
} else {
index && this.set(sigName, this.keys.sign(data), { signed: false })
return value
}
};

I realise that this answer is late in the day but might help someone with the same error. I was getting the error 'TypeError: this.keys.index is not a function' on line 73 of index.js in cookies when trying to use koa-session.
I eventually realised that I had set app.keys to a single value i.e.
app.keys = 'dieueyf7huienejnfef'
When it should be an array:
app.keys = ['dieueyf7huienejnfef']

Related

Problem Utf-8 decoding nodejs - Invalid continuation byte at readContinuationByte

I'm developping a nodejs server and i want to convert a csv file to a json file. I succeed this part, but on of my data ( the libelle_etape is not on a good format (utf8), the values are like: 'EII/MEA 5ème année' or 'Geau/STE 4ème année' etc...). So in my function i would like to decode those values to have the right format on my json file.
I have the result that i want when i do :
const result= utf8.decode(str)
BUT the problem is : when i want to remplace the old String that i have in my csv file (this one : "EII/MEA 5ème année") by the good one (result = "EII/MEA 5ème année") I have the following error :
*Unhandled rejection Error: Invalid continuation byte
at readContinuationByte *
The entire code is :
CSVToJSON()
.fromFile('./infoEtu.csv')
.then((source) => {
const oneData = source[0];
for (let i = 0; i < source.length; i++) {
for (let j = 0; j < Object.keys(source[i]).length; j++) {
const columnName = Object.keys(source[i]);
columnName.forEach((element) => {
if (element == 'Libelle_etape') {
const str = source[i]['Libelle_etape'];
const result = utf8.decode(str);
console.log(result); // this line show me the good result
source[i]['Libelle_etape'] = String(result); // this line is definitely the problem , i've tried with and withou de String() methods but it's the same error
}
});
}
}
const data = JSON.stringify(source);
FileSystem.writeFileSync('./jsonEtu.json', data);
});
Thank you in advance for your help, i'm searching for a long time now and i can find the same problem anywhere.
UPDATE :
The problem was because of the accents !
By doing that it's working :
const result = accents.remove(utf8.decode(str));
source[i]['Libelle_etape'] = result;

Null Commond line argument

I am passing around 9 parameter via command line to Node JS script.
Here is my Command:
node awsInvokeDelete.js DELETE https://Test1234.execute-api.us-west-2.amazonaws.com us-west-2 /qa/transit-connectivity/api/v1/sites/tdcloudtsttd03 AKIAJ4Y5DGqwewqeqw CFdAgsdtqweqwe/SKqDezdqweewofWrUXXBbQoMy '{\"change_request\":\"chg0123456\"}'
I am passing query parameter as JSON in command line argument which is process.argv[9] in node JS script. It works perfectly If I pass value to all parameters but in some cases process.argv[8] will be empty. When I am passing empty value in process.argv[8], its actually takes argv[9] as argv[8].
how Can I pass empty argument value in command line for below script.
var apigClientFactory = require('aws-api-gateway-client').default;
let awsMethod = process.argv[2],
awsEndpoint = process.argv[3],
awsRegion = process.argv[4],
awsPathTemplate = process.argv[5],
awsAccessKey = process.argv[6],
awsSecreteKey = process.argv[7],
awsPathParams = process.argv[8],
awsAdditionalParams = JSON.parse(process.argv[9] || '{}');
var apigClient = apigClientFactory.newClient({
invokeUrl: awsEndpoint, // REQUIRED
accessKey: awsAccessKey, // REQUIRED
secretKey: awsSecreteKey, // REQUIRED
region: awsRegion, // REQUIRED: The region where the API is deployed.
retryCondition: (err) => { // OPTIONAL: Callback to further control if
request should be retried. Uses axon-retry plugin.
return err.response && err.response.status === 500;
}
});
var param = awsPathParams;
// Template syntax follows url-template https://www.npmjs.com/package/url-template
var pathTemplate = awsPathTemplate;
var method = awsMethod;
var additionalParams = { queryParams: awsAdditionalParams, };
console.log(additionalParams);
var body = {};
apigClient.invokeApi(param, pathTemplate, method, additionalParams, body)
.then(function(result) {
//console.log(result.data + ": " +result)
console.log(result.response.data)
}).catch(function(result) {
console.log(result.response.data)
});
Here is output: args[8]'s value should be displayed as args[9]
args[8]: {"change_request":"chg0123456"}
args[9]: [object Object]
Your script is not working on the input that you have provided (if you actually add the missing argument) because '{\"change_request\":\"chg0123456\"}' is not something that JS can parse as a JSON string. Furthermore, you are not passing any empty value in your input to the script (just an empty space is not considered as an actual input).
You need to change it to this '{"change_request":"chg0123456"}' and pass empty value as an empty string ''.
This input works correctly.
node index.js DELETE https://Test1234.execute-api.us-west-2.amazonaws.com us-west-2 /qa/transit-connectivity/api/v1/sites/tdcloudtsttd03 AKIAJ4Y5DGqwewqeqw CFdAgsdtqweqwe/SKqDezdqweewofWrUXXBbQoMy '' '{"change_request":"chg0123456"}'
If you really need the object in that format, then you need to remove \ characters from it before you can call JSON.parse on it.
awsAdditionalParams = JSON.parse(
process.argv[9].split('\\').join('') || '{}'
);
If you first want to check whether the last argument is not empty and only then run the code above, the you can use ternary operator like this.
awsAdditionalParams = process.argv[9]
? JSON.parse(process.argv[9].split('\\').join('') || '{}')
: '';
3 options:
change the script to switch around arguments 8 and 9. then you always have the same number even if 9 is empty.
pass the argument as "" instead of nothing.
change the script so you parse your own command line and change things around whichever way you like.

unable to read empty cells reading excel file using js-xlsx

I have an excel file I am reading using js-xlsx. The code is working fine except where the cells are empty. These cells are ignored. How do I get these cells also when creating my JSON object?
I went through some of the question on SO as well as some other forums for the same problem but nothing satisfactory.
Any help would be welcome. My code is:
reader.addEventListener('load', function(){
var data = this.result;
var wb = XLSX.read(data, {type: 'binary', sheetStubs:true});
// console.log(headers);
wb.SheetNames.forEach(function(sheetName){
//pulling out column headers for tablecreation
var headers = get_header_row(wb.Sheets[sheetName]);
createTableInDB(headers);
// Here is your object
var XL_row_object = XLSX.utils.sheet_to_json(wb.Sheets[sheetName]);
//console.log(XL_row_object);
for(var i=0; i<XL_row_object.length; i++){
var json_object = XL_row_object[i];
if(json_object !== null){
var dataobject = {
"tablename": tname,
"dbname": dbname,
"info": json_object,
"uname": uname
}
dataobject = $.toJSON(dataobject);
$.ajax({
type: "POST",
url: "insertIntoTable.php",
async: false,
data:"pInsertData=" + dataobject,
success: function(msg){
console.log(msg);
}
});
//console.log(json_object);
}
}
});
});
reader.readAsBinaryString(document.querySelector('input').files[0]);
The file is uploaded through an input in HTML.
Thanks in Advance
Just pass default value in sheet_to_json method:
var jsonObj = XLS.utils.sheet_to_json(data.Sheets[data.SheetNames[0]], {
header: 0,
defval: ""
});
The library has an option for that. In your code below:
...
// Here is your object
var XL_row_object = XLSX.utils.sheet_to_json(wb.Sheets[sheetName]);
//console.log(XL_row_object);
...
You should provide the following option, to the options argument {defval: null} as follows:
...
// Here is your object
var XL_row_object = XLSX.utils.sheet_to_json(wb.Sheets[sheetName], {defval: null});
//console.log(XL_row_object);
...
Then, it should work.
Solution 1 .Condition "if(h===undefined)continue;" in "xlsx.core.min.js" comment it out.
or do it properly...
Solution 2 . By passing Condition extra param while running this XLSX.utils.sheet_to_json(wb.Sheets[name] , {blankCell : false}). add a condition on line no. 19150 "if(defval === undefined && blankCell) continue;" in file xlsx.js etc..

Firebase - Cloud Functions: enumerate [Object Object]

I would like to enumerate the members object from the below structure.
I do not have prior experience in node.js, I have tried the following code and it doesn't seem to work.
exports.sendVaultUnlockedPush = functions.database.ref('/Vaults/{id}/action').onUpdate(event => {
let status = event.data.val();
if (status == 'lock') {
var db = admin.database();
var vaultRef = db.ref("/Vaults/" + event.params.id);
vaultRef.once('value').then(function(snapshot) {
var hasMembers = snapshot.child('members');
if (hasMembers) {
var memberRef = db.ref("Vaults/" + event.params.id + "/members");
memberRef.once('value').then(function(memberSnapshot) {
memberSnapshot.forEach(function(element) {
console(element.key + " - " + element.val());
}, this);
});
}
});
}
})
It throws the following error:
Error: Firebase.DataSnapshot.forEach failed: Was called with 2 arguments. Expects no more than 1.
at Error (native)
at z (/user_code/node_modules/firebase-admin/lib/database/database.js:42:1666)
at T.forEach (/user_code/node_modules/firebase-admin/lib/database/database.js:114:179)
at /user_code/index.js:34:36
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
I would just like it to return the value of 'members' node. And I have no clue to do the same.
Any help is much appreciated in getting this sorted. Thanks!
According to the docs forEach takes only one parameter:
This should work:
var values;
memberSnapshot.forEach(function(element) {
console(element.key);
values = element.val();
for (var val in values) {
if (values.hasOwnProperty(val)) {
console(val, values[val]);
}
}
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Brunch plugin pipline issues

I'm writing a plugin for Brunch to 'filter' files from code library. Basic idea is to:
check my source files (in src\ folder, or any watched folders that don't match library pattern),
build a list of imported/required modules from code library (in lib\ folder, outside src\, somewhere on disk)
check files against this list and 'approve' or 'reject' them
compile only what's 'approved', so I don't end up with huge files that have all modules/components from my library, but only what I use in particular project
When I work only with JavaScript files this.pattern = /.*(js|jsx)$/; everything works fine. Next step is to include more files, since many modules/components in library have some sort of template or stylesheets, for example this is one AngularJS module:
lib\
modules\
pager\
controller.jsx
directive.jsx
template.html
pager.styl
README.md
But when I expand the pattern to include other files this.pattern = /.*/;, I run into all sorts of issues (; Most have to do with pipline - those are the kinds of errors I'm getting. For example:
jshint-brunch doesn't like README.md
html-brunch won't wrap template.html
stylus-brunch and sass-brunch are also unhappy
I've tried solving these problems individually, for example if I disable html-brunch config.plugins.off: ['html-brunch'], and add this code inside the compiler function, it kinda works:
if( params.path.match(/.html$/) ) {
params.data = "module.exports = function() { return " + JSON.stringify(params.data) + ";};";
return callback(null, this.config.modules.wrapper(params.path, params.data));
}
..but I couldn't resolve all the issues. Pretty much all problems have to do with this line in the compiler function: return callback(null, null);. When I 'reject' a file next plugin gets something undefined and breaks...
Any ideas how to solve this?
I'd like to eventually expand plugin's functionality to handle static assets too, for example copy lib\images\placeholder-1.jpg (but not placeholder-2.jpg) from library if it's used in html files, but I'm stuck at this point...
Here's the code of the plugin:
var CodeLibrary;
module.exports = CodeLibrary = (function() {
var required = [];
CodeLibrary.prototype.brunchPlugin = true;
function CodeLibrary(config) {
this.config = config;
this.pattern = /.*/;
this.watched = this.config.paths.watched.filter(function(path) {
return !path.match( config.plugins.library.pattern );
});
}
function is_required(path) {
var name = this.config.modules.nameCleaner(path);
return required.some(function(e, i, a) { return name.match(e); });
}
function in_library(path) {
return Boolean(path.match( this.config.plugins.library.pattern ));
}
function is_watched(path) {
return this.watched.some(function(e, i, a) { return path.match( e ); });
}
CodeLibrary.prototype.lint = function(data, path, callback) {
if( !is_watched.apply(this, [path]) &&
!is_required.apply(this, [path]) )
return callback();
var es6_pattern = /import .*'(.*)'/gm;
var commonjs_pattern = /require\('(.*)'\)/gm;
var match = es6_pattern.exec(data) || commonjs_pattern.exec(data);
while( match != null ) {
if( required.indexOf(match[1]) === -1 )
required.push( match[1] );
match = es6_pattern.exec(data) || commonjs_pattern.exec(data);
}
callback();
}
CodeLibrary.prototype.compile = function(params, callback) {
if( is_required.apply(this, [params.path]) ||
!in_library.apply(this, [params.path]) )
return callback(null, params);
return callback(null, null);
};
return CodeLibrary;
})();

Resources