How do I get a file name of currently executed spec?
For example:
I run: protractor conf.js --specs ./spec/first_spec.js,./spec/second_spec.js
so I want to retrieve array ['first_spec','second_spec'], because I want to show it in a report.html. Is this a good way of thinking or is there a built-in function for file names in the latest run? I'm new to protractor and angular, and I found only a way to extract individual describe which doesn't really help me. I write this on top of protractor-angular-screenshot-reporter.
This is one way of doing it. Read the array of test cases passed from CLI arguments and use it as per your convenience
onPrepare: function() {
var testCaseArr
for (i = 0; i < process.argv.length; i++) {
argument = process.argv[i];
// if "specs" are found we know that the immediate following object is the array of test scenarios
if (argument.indexOf('specs')>0) {
specIndex = i + 1;
testCaseArr = process.argv[i+1];
break;
}
}
// This will output - ['first_spec','second_spec']
console.log(testCaseArr)
},
Please refer my blog post for more details on the same.
Related
Normally I just add to the command files or the index file easily but it's starting to look messy. Recently I got this leveling system working
if (!levels[message.author.id]) {
levels[message.author.id] = {
level: 1,
exp: 0
}
}
// Gives random EXP
let randomExp = Math.floor(Math.random() * 5 + 5);
// Adds the random EXP to their current EXP
levels[message.author.id].exp += randomExp;
// Checks their EXP and changes their level
for (x = 0; x < expLevels.length; x++) {
if (levels[message.author.id].exp > expLevels[x]) {
levels[message.author.id].level = x + 1;
message.channel.reply(`congratulations! You reached level ${levels[message.author.id].level + 1}!`);
}
}
fs.writeFile('./levels.json', JSON.stringify(levels), err => {
if (err) console.error(err);
});
if (levels[authorMessage.author.id].level >= 10) {
message.member.roles.remove('720109209479413761');
message.member.roles.add('719058151940292659');
}
I would like to be able to put this into its own function and then call it in the "message" section for every time someone sends a message. Is that possible to do? Or no since I need to have access to the "message" variable?
I'm used to C++ with functions where it's much easier to deal with. Does anyone know if it's possible to code a bot in C++ or is there no support? If there is a way if someone can point me in the right direction to start please let me know. Otherwise I can easily stay with JS.
I'm not sure if a discord framework for C++ exists, probably but I'm not sure.
You can of course define a function somewhere and call it in the onMessage event.
There are two ways that you could do that.
In the same file
In another file
Functions in the same file.
You can declare a function and then pass arguments to that function. You don't need to declare the type of argument that is being passed here. Source
function leveling(message) { // here you can include all parameters that you might need
// the rest of your code
}
Once you have a function you can call it like this.
leveling(message); // here we pass the values we need to the function
Functions in a different file.
The concept is the same, however we need to export the function in order to use it somewhere else. There are two ways to do this, either export only one function or export all functions, in the case of a dedicated functions file this is the easier option.
Note: In this example I name the file functions.js and place it in the same directory as the file I require it from.
module.exports = {
// we need to declare the name first, then add the function
leveling: function (message) {
// the rest of your code
}
// here we can add more functions, divided by a comma
}
// if you want to export only one function
// declare it normally and then export it
module.exports = leveling;
Calling functions.
To use this function we need to require it in the file we want to use it in. Here we also have two options.
Either require the whole file and get the function from there
const myfunctions = require('./functions.js'); // this is the relative path to the file
// get the function via the new constant
myfunctions.leveling(message);
Or use Object destructuring to get only what you need from the exported functions.
const { leveling } = require('./functions.js');
leveling(message);
Both of these options provide advantages and disadvantages but in the end they both do the same.
First of all, yes I know this question has been asked before, but I still cannot figure out how to make it work. I believe the problem is, I am running files individually through node.js on my Mac terminal, sorta like applications.
Here is the deal. I have one file, bitt1.js, that has var mid = 293.03;.
In my other file, otherFile.js, I have an if, else statement, depending on the variable mid (which is in bitt1.js):
if (mid <= 290) {
trade = true;
} else {
trade = false; }
The issue is, in terminal, I run first bitt1.js, then after I run otherFile.js. This makes it so I can't receive the mid variable from bitt1.js and it comes up as undefined.
How can I solve this issue? I've only found things used within html or etc, where the variables are always "available".
I'm new to JS and this whole thing so some of the stuff I said may be incorrect... and I could have also just been being dumb and the answer is obvious, but please help me out... I've thought about creating a JSON file and writing/reading data from it using the two other files, but I feel there's a better way...
Thanks!
Developer NodeJS's code works if you don't want to modify the value of the variable - if you just want to share the initial value of the variable, it works perfectly.
But if you intend to mutate the value of mid during runtime execution of bitt1.js and want to use that value, perhaps you can use a Unix pipe to plug its value into the stdin of bitt1.js.
E.g.
// bitt1.js
var mid = 299;
console.log("<mid>%d</mid>", mid); // this is piped to stdin
// otherFile.js
var stdin = process.openStdin();
var data = "";
stdin.on('data', function(chunk) {
data += chunk;
});
stdin.on('end', function() {
data.match(/<mid>([\s\S]+)<\/mid>/i);
var mid = +data.match[1];
console.log(mid);
});
Then running: node bitt1.js | node otherFile.js
Would print 299 from within otherFile.js.
This is a rough solution though: it should require some undefined checking on the match expression, and of course piping doesn't allow you to print anything directly to console in the bitt1.js file - you'd have to reprint everything in otherFile.js, which leads to duplicate code.
But it could be a solution that works for you, all depends on your requirements! Hope this helps.
node.js allows imports and exports.
Say bitt1.js has:
var mid = 299
console.log(mid)
// Here is where you export the desired value
//export default mid
module.exports.mid = mid
Then, in your otherFile.js
// you import the value from bitt1.js
var mid = require('./bitt1')
console.log(mid) //Outputs 299
That's it.
Edit: updated answer
So, I'm a big fan of creating global namespaces in javascript. For example, if my app is named Xyz I normally have an object XYZ which I fill with properties and nested objects, for an example:
XYZ.Resources.ErrorMessage // = "An error while making request, please try again"
XYZ.DAL.City // = { getAll: function() { ... }, getById: function(id) { .. } }
XYZ.ViewModels.City // = { .... }
XYZ.Models.City // = { .... }
I sort of picked this up while working on a project with Knockout, and I really like it because there are no wild references to some objects declare in god-knows-where. Everything is in one place.
Now. This is ok for front-end, however, I'm currently developing a basic skeleton for a project which will start in a month, and it uses Node.
What I wanted was, instead of all the requires in .js files, I'd have a single object ('XYZ') which would hold all requires in one place. For example:
Instead of:
// route.js file
var cityModel = require('./models/city');
var cityService = require('./services/city');
app.get('/city', function() { ...........});
I would make an object:
XYZ.Models.City = require('./models/city');
XYZ.DAL.City = require('./services/city');
And use it like:
// route.js file
var cityModel = XYZ.Models.City;
var cityService = XYZ.DAL.City;
app.get('/city', function() { ...........});
I don't really have in-depth knowledge but all of the requires get cached and are served, if cached, from memory so re-requiring in multiple files isn't a problem.
Is this an ok workflow, or should I just stick to the standard procedure of referencing dependencies?
edit: I forgot to say, would this sort-of-factory pattern block the main thread, or delay the starting of the server? I just need to know what are the downsides... I don't mind the requires in code, but I just renamed a single folder and had to go through five files to change the paths... Which is really inconvenient.
I think that's a bad idea, because you are going to serve a ton of modules every single time, and you may not need them always. Your namespaced object will get quite monstrous. require will check the module cache first, so I'd use standard requires for each request / script that you need on the server.
Does anyone know how to get the name of a module in node.js / javascript
so lets say you do
var RandomModule = require ("fs")
.
.
.
console.log (RandomModule.name)
// -> "fs"
If you are trying to trace your dependencies, you can try using require hooks.
Create a file called myRequireHook.js
var Module = require('module');
var originalRequire = Module.prototype.require;
Module.prototype.require = function(path) {
console.log('*** Importing lib ' + path + ' from module ' + this.filename);
return originalRequire(path);
};
This code will hook every require call and log it into your console.
Not exactly what you asked first, but maybe it helps you better.
And you need to call just once in your main .js file (the one you start with node main.js).
So in your main.js, you just do that:
require('./myRequireHook');
var fs = require('fs');
var myOtherModule = require('./myOtherModule');
It will trace require in your other modules as well.
This is the way transpilers like babel work. They hook every require call and transform your code before load.
I don't know why you would need that, but there is a way.
The module variable, which is loaded automatically in every node.js file, contains an array called children. This array contains every child module loaded by require in your current file.
This way, you need to strict compare your loaded reference with the cached object version in this array in order to discover which element of the array corresponds to your module.
Look this sample:
var pieces = require('../src/routes/headers');
var childModuleId = discoverChildModuleId(pieces, module);
console.log(childModuleId);
function discoverChildModuleId(object, moduleObj) {
"use strict";
var childModule = moduleObj.children.find(function(child) {
return object === child.exports;
});
return childModule && childModule.id;
}
This code will find the correspondence in children object and bring its id.
I put module as a parameter of my function so you can export it to a file. Otherwise, it would show you modules of where discoverChildModule function resides (if it is in the same file won't make any difference, but if exported it will).
Notes:
Module ids have the full path name. So don't expect finding ../src/routes/headers. You will find something like: /Users/david/git/...
My algorithm won't detect exported attributes like var Schema = require('mongoose').Schema. It is possible to make a function which is capable of this, but it will suffer many issues.
From within a module (doesn't work at the REPL) you can...
console.log( global.process.mainModule.filename );
And you'll get '/home/ubuntu/workspace/src/admin.js'
I have some inline-javascript containing large datasets which are hard-coded into my PHP site:
var statsData = {
"times" : [1369008000,1369094400,1369180800,],
"counts" : [49,479,516,]
};
I'd like to refactor my code so that my variables are served with this structure:
[
[1369008000, 49],
[1369094400, 479],
[1369180800, 516],
]
However I have many files to update - are there any tools that would help automate this process?
Just create a new array then loop through the original one, and place the values according to the indexes:
var statsData = {"times":[1369008000,1369094400,1369180800,],"counts":[49,479,516,]};
var result = [];//Create a new array for results.
for (var i = 0; i < statsData.times.length; ++i){//Loop the original object's times property from 0 to it's length.
result.push([statsData.times[i], statsData.counts[i]]);//Push a new array to the result array in the new order that will contain the original values you acces throught the index in the loop variable.
}
console.log(result);
Also in your code you have two start [ in your object's counts attribute but only one ] closing it.
Carrying on from the comments; Trying to parse JS from a mix of PHP/HTML is horrible so if you are prepared to do some copying and pasting then - if it were me - I'd opt for a simple command-line tool. As your Javascript won't validate as JSON it doesn't make much sense to try and parse it in any other language.
I've knocked up a quick script to work with your current example (I'll leave it up to you to extend it further as needed). To run it you will need to install Node.js
Next, save the following where ever you like to organise files - lets call it statsData.js:
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(data){
try {
eval(data+';global.data=statsData');
processData();
} catch(e) {
process.stdout.write('Error: Invalid Javascript\n');
}
});
function processData(){
try {
var i, out = [];
while(i = data.times.shift())
out.push([i, data.counts.shift()||0]);
process.stdout.write('var statsData='+JSON.stringify(out)+';\n');
} catch(e) {
process.stdout.write('Error: Unexpected Javascript\n');
}
}
Now you have a CLI tool that works with standard I/O, to use it open a terminal window and run:
$ node path/to/statsData.js
It will then sit and wait for you to copy and paste valid javascript statements into the terminal, otherwise you could always pipe the input stream from a file where you have copied and pasted your JS to:
$ cat inputFile.js | node path/to/statsData.js > outputFile.js
cat is a unix command - if you are working on a windows machine I think the equivalent is type - but I'm unable to test that right now.