is there way to lint a specific variable name with eslint - javascript

For example, I want to eliminate a specific variable name like $abc or '$abc', if it exist anywhere, we will throw a linting error. Its specifically for es6 code or just javascript code.
How can I do that in eslint? is it possble?
If its not what is the alternative I can do to check that without pollute my code base?

You can create your own eslint rule as mentioned in the comments. Here is a small example that reports all identifiers (excluding property names) with name foo:
export default function(context) {
return {
Identifier(node) {
if (
node.name === 'foo' &&
(
node.parent.type !== 'MemberExpression' ||
node.parent.computed ||
node.parent.object === node
)
) {
context.report(node, 'Do not use the variable name "foo"');
}
}
};
};
Live example: http://astexplorer.net/#/Lmzgbm2iRq

You could traverse the codebase and check all the files for the presence of the variable you wish to eliminate. It's perhaps a bit heavyweight for what you need but it might be an option.
Something like this should do the trick. You will have to replace $bad_variable_name with whatever your actual
variable is. You will also have to do something to make your build fail (if desired)
var fs = require('fs');
var checkDir = (dir) => {
var files = fs.readdirSync(dir);
files.forEach((file) => {
var path = dir + '/' + file;
var stat = fs.statSync(path);
if (stat && stat.isDirectory()) {
checkDir(path);
} else {
if(path.endsWith('this-file.js')){ //the file where this code is
return;
}
var fileContents = fs.readFileSync(path);
if(fileContents.indexOf('$bad_variable_name') > -1){
console.log('$bad_variable_name found in ' + path);
//do something here to fail your build
}
}
});
};

Related

Why doesn't my .JSX script recognize every image in a folder which I want to mass-resize?

I have this JSX script I created but I feel like it's not checking for every file type in the filelist variable. Can someone take a look? It's very frustrating when I have it running and then for some reason a non-descript error message pops up and then it stops
Here is the script:
var inputFolder = Folder.selectDialog("Select a folder to process"),
fileList = inputFolder.getFiles(/\.(jpg|tif|psd|crw|cr2|nef|dcr|dc2|raw)$/i);
for(var i=0; i < fileList.length; i++) {
var doc = open(fileList[i]);
if(doc.width !== doc.height) {
if(doc.width > doc.height) {
doc.resizeCanvas(doc.width, doc.width)
} else {
doc.resizeCanvas(doc.height, doc.height)
}
}
if((doc.width && doc.height) > 1000) {
doc.resizeImage(1000, 1000);
} else {
doc.resizeImage(doc.width, doc.height);
}
doc.save();
doc.close();
}
This is the error message:
It seems that Folder.getFiles() doesn't accept RegExp objects, it only accepts a string or a function, beside that, it will also include Folder objects, you can change it to something like this to filter only files and only the file types you're interested in:
function filter(file) {
return (file instanceof File && /\.(jpg|tif|psd|crw|cr2|nef|dcr|dc2|raw)$/i.test(file.name))
}
fileList = inputFolder.getFiles(filter);

what's the best way to find the file in nested folders?

I found some legacy code where a factory load one file from sub-tree directory.
var name = 'file.js'
try {
return require('folder/foo/' + name)
} catch (e) {
try {
return require('folder/foo/bar/' + name)
} catch (ee) {
return null
}
}
How can I avoid the nested try/catch blocks for each folder level?
I tried this.
const name = 'file.js'
const pathList = ['folder/foo/', 'folder/foo/bar/']
return pathList.map(path => {
const file = `${path}${name}`
try {
return require(file).default
} catch (exception) {
return null
}
})
But this changes the behaviour. If the file is not found on first level it returns null instead of taking the next level. It doesn't help if I change the order at the pathList declaration.
Is there a better way in a React app environment? I cannot use FS from node.js.

ViewerJS str.replace how to make it work

I was taking a look at ViewerJS and seems like a good fit the only problem i found was title came out with %20 instead of space. I know why, but I cannot figure out how to fix it.
so it looks like this code gets worked first. how would i fix it in here to make it display with no %20.
function getPDFFileNameFromURL(url) {
var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
// SCHEME HOST 1.PATH 2.QUERY 3.REF
// Pattern to get last matching NAME.pdf
var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
var splitURI = reURI.exec(url);
var suggestedFilename = reFilename.exec(splitURI[1]) ||
reFilename.exec(splitURI[2]) ||
reFilename.exec(splitURI[3]);
if (suggestedFilename) {
suggestedFilename = suggestedFilename[0];
if (suggestedFilename.indexOf('%') !== -1) {
// URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
try {
suggestedFilename =
reFilename.exec(decodeURIComponent(suggestedFilename))[0];
} catch(e) { // Possible (extremely rare) errors:
// URIError "Malformed URI", e.g. for "%AA.pdf"
// TypeError "null has no properties", e.g. for "%2F.pdf"
}
}
}
return suggestedFilename || 'document.pdf';
}
var x = 'Some%20string%20with%20spaces';
x = x.replace(/%20/g, ' ');
console.log(x);

Javascript Rewrite Config File

I have a config.js file which I believe is JSON which is called when the application first starts:
var config={};
config.user = [
{id:'JSMITH', priceModify:'true'},
{id:'JBLOGGS', priceModify:'false'},
]
config.price = [
{id:"price01", name:"priceName01", primary:"57.25", secondary:"34.54"},
{id:"price02", name:"priceName02", primary:"98.26", secondary:"139.45"},
{id:"price03", name:"priceName03", primary:"13.87", secondary:"29.13"}
]
To pull / push data I just use the following:
// Read
var curPrice = config.price[0].primary;
// Write
config.price[0].primary = "98.24";
How do I go about exporting the config file with the new value so that it will load next time the application is opened? I can use the file system object to write the file, I just don't understand how I would export everything (and preferably keep the same format).
I originally thought about reading the whole config file into a variable, cycling through to find the required block, id, and key and replacing the value, then writing the whole thing back, but I can't seem to figure out how to replace that specific value only.
Any help would be greatly appreciated
Edit Apologies, I forgot to mention that this application is completely offline and uses local directories
Solution
I stumbled across a few solutions to different issues which, when combined, gave me the perfect solution. First we cycle the Javascript object, building an array of the detail and then converting the array to a string:
vMethod.convertToText = function(obj) {
var string = [];
var output = '';
var count= 0;
var countTotal = 0;
if (typeof(obj) == "object" && (obj.join == undefined)) {
count= 0;
countTotal = 0;
string.push("{");
for (prop in obj) {
countTotal++;
}
for (prop in obj) {
if(count==countTotal - 1) {
string.push(prop, ": ", vMethod.convertToText(obj[prop]),'}\r\n');
} else {
string.push(prop, ": ", vMethod.convertToText(obj[prop]), ",");
}
count++;
};
} else if (typeof(obj) == "object" && !(obj.join == undefined)) {
count= 0;
countTotal = 0;
string.push("[\r\n")
for (prop in obj) {
countTotal++;
}
for(prop in obj) {
if(count==countTotal - 1) {
string.push(vMethod.convertToText(obj[prop]),'];\r\n');
} else {
string.push(vMethod.convertToText(obj[prop]), ",");
}
count++;
}
} else if (typeof(obj) == "function") {
string.push(obj.toString())
} else {
string.push(JSON.stringify(obj))
}
output = string.join("").toString();
//output = output.slice(1, -1);
return output;
}
Then we clean the array (neccessary for me to remove excess characters)
vMethod.cleanConfigText = function() {
var outputText = vMethod.convertToText(config);
outputText = outputText.slice(1, -1);
outputText = 'var config = {};\r\n'+outputText;
outputText = outputText.replace('user:','config.user =');
outputText = outputText.replace(',price:','config.price =');
outputText = outputText.slice(0, -2);
outputText = outputText.replace(/"/g, "'")
return outputText;
}
Finally a function to export the object into my config.js file:
vMethod.writeToConfig = function() {
vObject.fileSystem = new ActiveXObject('Scripting.FileSystemObject');
vObject.fileSystemFile = vObject.fileSystem.CreateTextFile('source\\js\\config.js',true);
vObject.fileSystemFile.Write(vMethod.cleanConfigText());
vObject.fileSystemFile.Close();
delete vObject.fileSystemFile;
delete vObject.fileSystem;
}
So when I want to export a change in the config, I just call:
vMethod.writeToConfig();
The only difference in the file format is that the commas appear at the start of a trailing line rather than the end of a preceding line but I can live with that!
Edit Turns out I'm anally retentive and the commas were bugging me
Added these to the clean up function and now the config is identical to before but without the indent
outputText = outputText.replace(/[\n\r]/g, '_');
outputText = outputText.replace(/__,/g, ',\r\n');
outputText = outputText.replace(/__/g, '\r\n');
Thank you to those that looked at the question and tried to help, very much appreciated.
Edit
DO NOT READ THE SOLUTION ABOVE, IT IS IN THE WRONG PLACE AND THERFORE IS NOT A VALID ANSWER. YOU'VE BEEN WARNED.
You can use a very popular npm package: https://www.npmjs.com/package/jsonfile . There are many but I've choosen this one.
Usually config stuff should be in json or .env files.
Now, all you have to do is use jsonfile's API to read/write JSON and parse (the package does the serialization/deserialization) it at the beginning when the application starts.
Example:
var jsonfile = require('jsonfile');
var util = require('util');
var config = null;
var file = './config.json';
// Reading
jsonfile.readFile(file, function(err, obj) {
config = obj;
});
// Writing
// Edit your config blah blah
config.user = [
{id:'JSMITH', priceModify:'true'},
{id:'JBLOGGS', priceModify:'false'},
];
config.price = [
{id:"price01", name:"priceName01", primary:"57.25", secondary:"34.54"},
{id:"price02", name:"priceName02", primary:"98.26", secondary:"139.45"},
{id:"price03", name:"priceName03", primary:"13.87", secondary:"29.13"}
];
jsonfile.writeFile(file, config, function (err) {
if(err) return err;
console.log('Config saved to file!');
});

Filter nesting failed in Jade

I have some filters:
var jade = require('jade');
jade.filters.Posts = function(block) {
return '{block:Posts}'+jade.render(block)+'{/block:Posts}';
};
jade.filters.Audio = function(block) {
return '{block:Audio}'+jade.render(block)+'{/block:Audio}';
};
jade.filters.Video = function(block) {
return '{block:Video}'+jade.render(block)+'{/block:Video}';
};
And have some input
:Posts
Posts
:Audio
| Audio
:Video
| Video
So I have an error:
>> unknown filter ":Audio"
Can I handle or fix this problem?
PS You can look at the code in this repository — I'm using grunt and grunt-contrib-jade plugin, but to force grunt-contrib-jade work with filters you should edit ./node_modules/grunt-contrib-jade/tasks/jade.js to reflect changes from this pull request.
PS2: I found the stumbling block. When I use render() method inside filter, I invoke it from local jade instance, which is don't know anything about filters, but global jade instance (from Gruntfile.js) have all information about that filters. That's why the main question is: how can I throw global Jade-instance to file with filters?
PS3: I don't know how create fiddle for such case. But you can clone my Hampi repo, implement changes to grunt-contrib-jade from my PR to them, then at start run npm i. To compile templates run grunt jade. Pay attention to these line in body.jade and commented section in filters.
PS4. I find the reason and it in different scope. I describe it with details here. Can you solve this issue?
I'm open to additional answers and I will accept fixes in jade core (if it would be required).
We just should bind global jade instance to filters like this:
var jade = require('jade');
if (options.filters) {
// have custom filters
Object.keys(options.filters).forEach(function(filter) {
if (_.isFunction(data)) {
// have custom options
jade.filters[filter] = options.filters[filter].bind({jade: jade, locals: data()});
} else {
// have no custom options
jade.filters[filter] = options.filters[filter].bind({jade: jade });
}
});
}
See implementation here — in this commit
I think you are right at problem place, the problem is in the filter.js file
location jade/lib/filters.js
var transformers = require('transformers');
module.exports = filter;
function filter(name, str, options) {
if (typeof filter[name] === 'function') {
var res = filter[name](str, options);
} else if (transformers[name]) {
var res = transformers[name].renderSync(str, options);
if (transformers[name].outputFormat === 'js') {
res = '<script type="text/javascript">\n' + res + '</script>';
} else if (transformers[name].outputFormat === 'css') {
res = '<style type="text/css">' + res + '</style>';
} else if (transformers[name].outputFormat === 'xml') {
res = res.replace(/'/g, ''');
}
} else {
throw new Error('unknown filter ":' + name + '"');
}
return res; // returns RES that is not defined in scope of function.
}
filter.exists = function (name, str, options) {
return typeof filter[name] === 'function' || transformers[name];
};
Here I have identified one flaw that you can correct like this,
var transformers = require('transformers');
module.exports = filter;
function filter(name, str, options) {
var res;//defined a variable which is global to the scope of function.
if (typeof filter[name] === 'function') {
res = filter[name](str, options);
} else if (transformers[name]) {
res = transformers[name].renderSync(str, options);
if (transformers[name].outputFormat === 'js') {
res = '<script type="text/javascript">\n' + res + '</script>';
} else if (transformers[name].outputFormat === 'css') {
res = '<style type="text/css">' + res + '</style>';
} else if (transformers[name].outputFormat === 'xml') {
res = res.replace(/'/g, ''');
}
} else {
throw new Error('unknown filter ":' + name + '"');
}
return res;
}
filter.exists = function (name, str, options) {
return typeof filter[name] === 'function' || transformers[name];
};
It may be possible that nesting under some function makes audio function out of scope. Does audio function works alone!?
although there may be other things if the problem not solved, please create a fiddle for your for better understanding.

Categories