How to strip comments in javascript? - javascript

I have multiple files that start with comments like:
/*
* #title Force email verification
* #overview Only allow access to users with verified emails.
* #gallery true
* #category access control
*
* This rule will only allow access users that have verified their emails.
*
* > Note: It might be a better UX to make this verification from your application.
*
* If you are using [Lock](https://auth0.com/docs/lock), the default behavior is to log in a user immediately after they have signed up.
* To prevent this from immediately displaying an error to the user, you can pass the following option to `lock.show()` or similar: `loginAfterSignup: false`.
*
* If you are using [auth0.js](https://auth0.com/docs/libraries/auth0js), the equivalent option is `auto_login: false`.
*
*/
//jshint -W025
function (user, context, callback) {
if (!user.email_verified) {
return callback(new UnauthorizedError('Please verify your email before logging in.'));
} else {
return callback(null, user, context);
}
}
All files contains two types of comments i.e /**/ and // Now I am reading this file in my javascript code and want to remove comments and get the actual code in the variable e.g
function (user, context, callback) {
if (!user.email_verified) {
return callback(new UnauthorizedError('Please verify your email before logging in.'));
} else {
return callback(null, user, context);
}
}
I have tried using strip-comments and parse-comments npm but none of these work. Here is the code:
const fs = require('fs');
const path = require('path');
const strip = require('strip-comments');
module.exports = function (ruleFileName, globals, stubs) {
globals = globals || {};
stubs = stubs || {};
const fileName = path.join(__dirname, '../src/rules', ruleFileName + '.js');
const data = fs.readFileSync(fileName, 'utf8');
const code = strip(data);
console.log(code);
return compile(code, globals, stubs);
}
and with parse-comments I tried like:
const parsed = parseComments(data)[0];
const code = data.split('\n').slice(parsed.comment.end).join('\n').trim();
I think strip comment is not working because it takes string as an argument but fs.readFileSync doesn't return string. I have also tried data.toString()but that also didn't work. So how can I strip comments from the content? Is there any other solution?

try use regx to replace /\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/gm
var Text = `/*
* #title Force email verification
* #overview Only allow access to users with verified emails.
* #gallery true
* #category access control
*
* This rule will only allow access users that have verified their emails.
*
* > Note: It might be a better UX to make this verification from your application.
*
* If you are using [Lock](https://auth0.com/docs/lock), the default behavior is to log in a user immediately after they have signed up.
* To prevent this from immediately displaying an error to the user, you can pass the following option to "lock.show()" or similar: "loginAfterSignup: false".
*
* If you are using [auth0.js](https://auth0.com/docs/libraries/auth0js), the equivalent option is "auto_login: false".
*
*/
//jshint -W025
function (user, context, callback) {
if (!user.email_verified) {
return callback(new UnauthorizedError('Please verify your email before logging in.'));
} else {
return callback(null, user, context);
}
}`
console.log(Text.replace(/\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/gm,''))
like this
https://codepen.io/anon/pen/eQKrWP

Related

how to apply javascript promises for async data hashing

In an online blockchain developer course I am participating in, one prerequisite was javascript object oriented & async programming, which I do not have experience in. However, having some experience in programming, I figured I would just learn as I go.
A practice activity (not a graded one, those I can not get help on) on blockchain hashing wants us to create an async hashing function using promises to hash data with SHA256. There are 2 main files: app.js, and block.js .
app.js (this was given to us, it is the main file we run):
/**
* Importing the Block class
*/
//
const BlockClass = require('./block.js');
/**
* Creating a block object
*/
const block = new BlockClass.Block("Test Block");
// Generating the block hash
block.generateHash().then((result) => {
console.log(`Block Hash: ${result.hash}`);
console.log(`Block: ${JSON.stringify(result)}`);
}).catch((error) => {console.log(error)});
/**
* Step 3: Run the application in node.js
*
*/
// From the terminal: cd into Project folder
// From the terminal: Run node app.js to run the code
block.js ( the arrows indicate the part I added myself, everything else was given.
/**
* Import crypto-js/SHA256 library
*/
const SHA256 = require('crypto-js/sha256');
/**
* Class with a constructor for block
*/
class Block {
constructor(data){
this.id = 0;
this.nonce = 144444;
this.body = data;
this.hash = "";
}
/**
* Step 1. Implement `generateHash()`
* method that return the `self` block with the hash.
*
* Create a Promise that resolve with `self` after you create
* the hash of the object and assigned to the hash property `self.hash = ...`
*/
//
generateHash() {
// Use this to create a temporary reference of the class object
let self = this;
> //Implement your code here
> self.hash = SHA256(JSON.stringify(self.body));
> const promise = new Promise(function(myResolve,myReject){
> if(self.hash = SHA256(JSON.stringify(self.body))){
> myResolve(self);
> }else{
> myReject(Error("It Broke"));
> }
>
> });
>
> promise.then(
> function(result){this.hash = result.hash;},
> function(error){console.log(error);}
> );
> }
}
// Exporting the class Block to be reuse in other files
module.exports.Block = Block;
Utilizing online resources, I do sort of understand promises, but not really- and definitely not how to apply them here. I was hoping I could get some help on this.

PhpStorm unused property warning using res.json in Node.js

I have these 2 functions in AssessmentController.js:
/**
* Get all assessments
*
* #param req
* #param res
* #returns {Promise<void>}
*/
static async GetAll(req, res) {
try {
let assessments = await Assessment.GetAll(req.query);
res.json({
msg: 'Assessments were listed successfully.',
assessments //This is marked as unused property
});
} catch (err) {
CustomError.handle(err, res);
}
}
/**
* Get a single assessment
*
* #param req
* #param res
* #returns {Promise<void>}
*/
static async GetAssessment(req, res) {
try {
let assessment = await Assessment.GetAssessment(req.params.id);
res.json({
msg: 'Assessment is retrieved successfully',
assessment //This is NOT marked as unused property
})
} catch (err) {
CustomError.handle(err, res);
}
}
The return types in JSDoc of the functions GetAll and GetAssessment are #returns {Promise<Object[]>} and #returns {Promise<Object>} respectively.
I don't know why passing assessments property to res.json in the first function (GetAll) triggers unused variable although this is not happening in the second function (GetAssessment).
Please let me know in the comments if you need any more information as I don't know where exactly to look for the problem.
Here is a snapshot of what I'm seeing:
NOTE:
Even if I don't use shorthand property (assessments: assessments) I get the warning.
I have also discovered just now that if I rename the variable to assessment (Singular) the warning is gone, how can I trace this problem?
Another example, it happens very randomly and I am showing images to see what I'm facing:
Maybe it is an IDE bug?
This issue is tracked at WEB-38106, please follow it for updates
You can try this:
assessments: assessments
instead of assessments.
Maybe your ide doesn't understand it.

How do I use nodejs Mysql package to get my data into the function after callback

So I'm trying to use nodejs mysql to access my locally running database that I am using for development. Everything is running correctly and I am able to make successful queries to the server and get the data back.
I have the function I created below which I am module.exports so that it is accessible from within my server where it is invoked and the loadExp() method is called.
var dataStore = function (connection) {
this.con = connection;
this.clientArr = new Map();
/**
* Loads all of the user experiences into the array.
*/
this.loadExp = function () {
var output = 'err';
loadData(this.con, function (err, result) {
console.log(err || result);
output = result.uuid;
});
console.log(output);
};
function loadData(con, callback) {
con.query('SELECT * FROM exp', function (err, rows, fields) {
if (err) throw err;
callback(null, rows);
});
}
/**
* Returns the value of a client from within the hash map.
* #param id
* #returns {*|String}
*/
this.getClient = function (id) {
var value = this.clients.get(id);
if (value != null) {
return value;
} else {
return 'err';
}
};
/**
* Returns a full list of clients.
* #returns {Map}
*/
this.getClientList = function () {
return this.clientArr;
};
/**
* Creates a new instance of a client within the database and also within our datastore.
* #param id
* #param client
*/
this.addClient = function (id, client) {
this.clientArr.set(id, client);
};
};
module.exports = dataStore;
Now I would like to make use of my this.addClient function outlined at the bottom of this function but I can never get my data in scope to make this possible and I'm stuck for how I would get this data in scope so that it is usable.
This is a problem with lexical scoping in JavaScript (ES5). You need to make sure the this is what you think it is when called. this is bound to the object the function was called within.
Look into setting var self = this at the top of your parent function and using that as a reference. Or, even better, using .bind(this).

Check if database exists using phonegap

i need check if exists an database creating in my application with phonegap.
Searching lot but i dont nothing found.
I found content just talking about tables that already exist but nothing talking about how to verify that the database created exists.
Thanks!
I followed a path as follows.
var db;
function createDataBase(fn){
try{
db = window.openDatabase('example.db','1','Example Database',-1, function(){
/**
* database first created ...
*
* */
createTables(fn);
});
}catch(e){
/**
* database already created!!
* */
db = window.openDatabase('readyVehicle.db','','',-1);
if(typeof(fn) == 'function'){
fn.call(null, db);
}
}
}
function createTables(fn){
....
....
if(typeof(fn)=='function'){
fn.call(null, db);
}
}
createDataBase(function(db){
// dosomething();
})

Trying to get JavaScript code completion to work in netbeans with jsdoc

In my app.js I have the following:
angular.module('app').controller('userList',
['appSettings'
,function (/*#type {app.appSettings}*/appSettings) {
appSettings.<<== it shows a list here but nothing from autocomplete.js
In my autocomplete.js I have the following (generated by JavaScript printing out my services and their members):
var app={};
app.appSettings={};
app.appSettings.userFailMessages={};
app.appSettings.userFailMessages.invalidJson
="Invalid request, user sent is not valid json.";
NetBeans refuses to code complete appSettings for me and doesn't seem to know it's defined in autocomplete.js. Maybe I'm getting my js doc wrong but tried a mix of combination of #var, #type and #param without success.
It code completes when I type app.appSettings. and gives me a list from autocomplete.js but I would like to know how I can tell NetBeans that the passed argument to the function is app.appSettings.
Maybe I should have autocomplete contain constructor functions instead of object literals as #type suggests a certain type and not an instance.
This is NetBeans 7.3.1
Was close to the answer, to have NetBeans use type you have to define the type. Then to indicate that the parameters passed to your angular module (or any function) are of a certain type I use the #param jsdoc
The angular module:
angular.module('app').controller('userList'
, ['$scope','appRules','appSettings'
,/**
* #param {app.appRules} appRules
* #param {app.appSettings} appSettings
* */
function ($scope,appRules,appSettings,$timeout) {
//<== here both appRules and appSettings give suggestions
// from autocomplete
autocomplete.js (not included in my html file but just there for code suggest)
/*#typedef {Object} app*/
var app={};
app.appRules={};
app.appRules.userIsInRole=function (user,role){};
app.appRules.general={};
app.appRules.general.isEmpty=function (val){};
app.appRules.general.isEmail=function (val){};
app.appSettings={};
app.appSettings.userFailMessages={};
app.appSettings.userFailMessages.invalidJson
="Invalid request, user sent is not valid json.";
app.appSettings.userFailMessages.noPrivilege
="You do not have the privileges needed to change this user.";
I ran the following code in the console on a page that contains my app to generate autocomplete.js:
var inj;
function allServices(mod, r) {
if (!r) {
r = {};
inj = angular.element(document.querySelector('[data-ng-app]')).injector().get;
}
angular.forEach(angular.module(mod).requires, function(m) {
allServices(m, r)
});
angular.forEach(angular.module(mod)._invokeQueue, function(a) {
try {
r[a[2][0]] = inj(a[2][0]);
} catch (e) {
}
});
return r;
};
var output=[];
function addOutput(names,prop){
if(names.length===1){
output.push('var ');
}
output.push(names.join('.'));
if(typeof prop === 'object'){
output.push('={};\n');
for(thing in prop){
//TODO: no arrays or route paths
if(/[0-9\/\\]/.test(thing)){
continue;
}
names.push(thing);
addOutput(names,prop[thing]);
}
}else{
output.push('=');
output.push(
(typeof prop === 'function')?
prop.toString():
JSON.stringify(prop)
);
output.push(';\n');
}
names.pop();
}
function createOutput(){
allMyServices = allServices('app');
addOutput(['app'],allMyServices);
console.log(output.join(''));
}
createOutput();

Categories