How can I retrieve the MyDocuments path with NodeJS.
So I would like to get something in NodeJs with the following C# code:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Thx & Regards
Stefan
Found the answer:
var Q = require('Q');
var getUserDoc = function(callback) {
var Winreg = require('winreg');
var deferred = Q.defer();
var regKey = new Winreg({
hive: Winreg.HKCU,
key: '\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders'
});
var myDocFolder = regKey.values(function(err, items) {
for (var i in items) {
if (items[i].name === 'Personal') {
deferred.resolve(items[i].value);
}
}
});
deferred.promise.nodeify(callback);
return deferred.promise;
}
getUserDoc().then(function(result) {
console.log(result);
});
You should use the environment variable instead :
function getUserDoc() {
return process.env.USERPROFILE+'\\Documents';
}
This assumes that you run Win7 or above. For Win XP, it'd be \\My Documents. You can easily check for one or the other in your function.
Also, you can use the package path-extra which offers the shortcut homedir()
In this case you'd have to do :
var path = require('path-extra');
function getUserDoc() {
return path.homedir()+'\\Documents';
}
Both of these solutions allow you to not give your app the credentials for checking the registry.
And run way faster than the promise + registry hack you've found.
Update: path-extra do not supports homedir any more. https://github.com/jprichardson/node-path-extra/commit/ce7a0b67ce07ca06ca2eeabf62621e1327b1d113
+1 for ingenuity though, I've saved that snippet for possible use ;-)
Related
How do I override Keyboard Shortcuts in Firefox so that it can be picked up by web page
For example, I have a webpage that detects ctrl-shift-h which worked fine in version 56 but now in version 96 it brings up a "Show All History" dialog
I am doing many such things so I looking for a generic way to override Firefox keyboard shortcuts
I found a way by adding two files under the Firefox directory
Firefox64\defaults\pref\config-prefs.js
pref("general.config.filename", "config.js");
pref("general.config.obscure_value", 0);
pref("general.config.sandbox_enabled", false);
Firefox64\config.js
let { classes: Cc, interfaces: Ci, manager: Cm } = Components;
const {Services} = Components.utils.import('resource://gre/modules/Services.jsm');
function ConfigJS() { Services.obs.addObserver(this, 'chrome-document-global-created', false); }
ConfigJS.prototype = {
observe: function (aSubject) { aSubject.addEventListener('DOMContentLoaded', this, {once: true}); },
handleEvent: function (aEvent) {
let document = aEvent.originalTarget; let window = document.defaultView; let location = window.location;
if (/^(chrome:(?!\/\/(global\/content\/commonDialog|browser\/content\/webext-panels)\.x?html)|about:(?!blank))/i.test(location.href)) {
if (window._gBrowser) {
let keys = ["key_find", "key_findAgain", "key_findPrevious", "key_gotoHistory", "addBookmarkAsKb", "bookmarkAllTabsKb", "showAllHistoryKb", "manBookmarkKb", "viewBookmarksToolbarKb", "key_savePage", "key_search", "key_search2", "focusURLBar", "focusURLBar2", "key_openDownloads", "openFileKb", "key_reload_skip_cache", "key_viewSource", "key_viewInfo", "key_privatebrowsing", "key_quitApplication", "context-bookmarklink"];
for (var i=0; i < keys.length; i++) {
let keyCommand = window.document.getElementById(keys[i]);
if (keyCommand != undefined) {
keyCommand.removeAttribute("command");
keyCommand.removeAttribute("key");
keyCommand.removeAttribute("modifiers");
keyCommand.removeAttribute("oncommand");
keyCommand.removeAttribute("data-l10n-id");
}
}
}
}
}
};
if (!Services.appinfo.inSafeMode) { new ConfigJS(); }
You can get a list of ids for the keys from the source by putting the following URL in your browser
view-source:chrome://browser/content/browser.xhtml
Sorry I can't comment yet but to extend zackhalil answer:
For those on Linux or simillar Unix/Unix-like systems replace Firefox64 for /usr/lib/firefox. Don't be confused with $HOME/.mozilla/firefox
How can we resolve promise to a normal number value .
I have use case in protractor automation in the first i have to call a asynchronous operation then that result value which should not be a promise .
I am using protractor framework
EDIT
var mobileNumber = database.generateMobileNumber().then(function(mobileNumber){
done();
return mobileNumber;
});
var number=Promise.resolve(mobileNumber);
Not quite sure why you might want to work with non-promise values, but i think you should play with browser.wait()
I didn't checked this, test this code to see if it will work.
This approach is bad, think twice before use it:
function getMobileNumber() {
var result;
var promise = database.generateMobileNumber().then(mobileNumber=> {
result = mobileNumber;
return true;
});
browser.wait(promise, 10000)
return result;
}
How about this ? You can find in this article more information about managing promises with protractor.
var mobileNumber = database.generateMobileNumber().then(function(mobileNumber){
done();
var deferred = protractor.promise.defer();
return deferred.fulfill(mobileNumber);
});
EDIT
var mobileNumber = database.generateMobileNumber().then(function(value){
done();
var deferred = protractor.promise.defer();
return deferred.fulfill(value);
});
the previous one is not clean as the same name (mobileNumber) is used in two different contexts. I don't know the result of this.
I'm trying to add a simple drop down control above a list such that I can sort it by "created" or "title".
The list template is called posts_list.html. In it's helper .js file I have:
posts: function () {
var sortCriteria = Session.get("sortCriteria") || {};
return Posts.find({},{sort: {sortCriteria: 1}});
}
Then, I have abstracted the list into another template. From here I have the following click event tracker in the helper.js
"click": function () {
// console.log(document.activeElement.id);
Session.set("sortCriteria", document.activeElement.id);
// Router.go('history');
Router.render('profile');
}
Here I can confirm that the right Sort criteria is written to the session. However, I can't make the page refresh. The collection on the visible page never re-sorts.
Frustrating. Any thoughts?
Thanks!
You can't use variables as keys in an object literal. Give this a try:
posts: function() {
var sortCriteria = Session.get('sortCriteria');
var options = {};
if (sortCriteria) {
options.sort = {};
options.sort[sortCriteria] = 1;
}
return Posts.find({}, options);
}
Also see the "Variables as keys" section of common mistakes.
thanks so much for that. Note I've left commented out code below to show what I pulled out. If I required a truly dynamic option, versus the simply binary below, I would have stuck w/ the "var options" approach. What I ended up going with was:
Template.postList.helpers({
posts: function () {
//var options = {};
if (Session.get("post-list-sort")) {
/*options.sort = {};
if (Session.get("post-list-sort") == "Asc") {
options.sort['created'] = 1;
} else {
options.sort['created'] = -1;
}*/
//return hunts.find({}, options);}
console.log(Session.get("hunt-list-sort"));
if (Session.get("hunt-list-sort") == "Asc") {
return Hunts.find({}, {sort: {title: 1}});
}
else {
return Hunts.find({}, {sort: {title: -1}});
};
}
}
});
I'm pretty new to CasperJS, but isn't there a way to open a URL and execute CasperJS commands in for loops? For example, this code doesn't work as I expected it to:
casper.then(function() {
var counter = 2013;
for (i = counter; i < 2014; i++) {
var file_name = "./Draws/wimbledon_draw_" + counter + ".json";
// getting some local json files
var json = require(file_name);
var first_round = json["1"];
for (var key in first_round) {
var name = first_round[key].player_1.replace(/\s+/g, '-');
var normal_url = "http://www.atpworldtour.com/Tennis/Players/" + name;
// the casper command below only executes AFTER the for loop is done
casper.thenOpen(normal_url, function() {
this.echo(normal_url);
});
}
}
});
Instead of Casper is calling thenOpen on each new URL per iteration, it gets only called AFTER the for loop executes. Casper thenOpen then gets called with the last value normal_url is set to. Is there no Casper command to have it work each iteration within the for loop?
Follow up: How do we make casper thenOpen return a value on the current iteration of the for loop?
Say for example, I needed a return value on that thenOpen (maybe if the HTTP status is 404 I need to evaluate another URL so I want to return false). Is this possible to do?
Editing casper.thenOpen call above:
var status;
// thenOpen() only executes after the console.log statement directly below
casper.thenOpen(normal_url, function() {
status = this.status(false)['currentHTTPStatus'];
if (status == 200) {
return true;
} else {
return false;
}
});
console.log(status); // This prints UNDEFINED the same number of times as iterations.
If you need to get context then use the example here:
https://groups.google.com/forum/#!topic/casperjs/n_zXlxiPMtk
I used the IIFE (immediately-invoked-function-expression) option.
Eg:
for(var i in links) {
var link = links[i];
(function(index) {
var link = links[index]
var filename = link.replace(/#/, '');
filename = filename.replace(/\//g, '-') + '.png';
casper.echo('Attempting to capture: '+link);
casper.thenOpen(vars.domain + link).waitForSelector('.title h1', function () {
this.capture(filename);
});
})(i);
}
links could be an array of objects and therefore your index is a reference to a group of properties if need be...
var links = [{'page':'some-page.html', 'filename':'page-page.png'}, {...}]
As Fanch and Darren Cook stated, you could use an IIFE to fix the url value inside of the thenOpen step.
An alternative would be to use getCurrentUrl to check the url. So change the line
this.echo(normal_url);
to
this.echo(this.getCurrentUrl());
The problem is that normal_url references the last value that was set but not the current value because it is executed later. This does not happen with casper.thenOpen(normal_url, function(){...});, because the current reference is passed to the function. You just see the wrong url, but the correct url is actually opened.
Regarding your updated question:
All then* and wait* functions in the casperjs API are step functions. The function that you pass into them will be scheduled and executed later (triggered by casper.run()). You shouldn't use variables outside of steps. Just add further steps inside of the thenOpen call. They will be scheduled in the correct order. Also you cannot return anything from thenOpen.
var somethingDone = false;
var status;
casper.thenOpen(normal_url, function() {
status = this.status(false)['currentHTTPStatus'];
if (status != 200) {
this.thenOpen(alternativeURL, function(){
// do something
somethingDone = true;
});
}
});
casper.then(function(){
console.log("status: " + status);
if (somethingDone) {
// something has been done
somethingDone = false;
}
});
In this example this.thenOpen will be scheduled after casper.thenOpen and somethingDone will be true inside casper.then because it comes after it.
There are some things that you need to fix:
You don't use your counter i: you probably mean "./Draws/wimbledon_draw_" + i + ".json" not "./Draws/wimbledon_draw_" + counter + ".json"
You cannot require a JSON string. Interestingly, you can require a JSON file. I still would use fs.read to read the file and parse the JSON inside it (JSON.parse).
Regarding your question...
You didn't schedule any commands. Just add steps (then* or wait*) behind or inside of thenOpen.
I'm using LESS CSS (more exactly less.js) which seems to exploit LocalStorage under the hood. I had never seen such an error like this before while running my app locally, but now I get "Persistent storage maximum size reached" at every page display, just above the link the unique .less file of my app.
This only happens with Firefox 12.0 so far.
Is there any way to solve this?
P.S.: mainly inspired by Calculating usage of localStorage space, this is what I ended up doing (this is based on Prototype and depends on a custom trivial Logger class, but this should be easily adapted in your context):
"use strict";
var LocalStorageChecker = Class.create({
testDummyKey: "__DUMMY_DATA_KEY__",
maxIterations: 100,
logger: new Logger("LocalStorageChecker"),
analyzeStorage: function() {
var result = false;
if (Modernizr.localstorage && this._isLimitReached()) {
this._clear();
}
return result;
},
_isLimitReached: function() {
var localStorage = window.localStorage;
var count = 0;
var limitIsReached = false;
do {
try {
var previousEntry = localStorage.getItem(this.testDummyKey);
var entry = (previousEntry == null ? "" : previousEntry) + "m";
localStorage.setItem(this.testDummyKey, entry);
}
catch(e) {
this.logger.debug("Limit exceeded after " + count + " iteration(s)");
limitIsReached = true;
}
}
while(!limitIsReached && count++ < this.maxIterations);
localStorage.removeItem(this.testDummyKey);
return limitIsReached;
},
_clear: function() {
try {
var localStorage = window.localStorage;
localStorage.clear();
this.logger.debug("Storage clear successfully performed");
}
catch(e) {
this.logger.error("An error occurred during storage clear: ");
this.logger.error(e);
}
}
});
document.observe("dom:loaded",function() {
var checker = new LocalStorageChecker();
checker.analyzeStorage();
});
P.P.S.: I didn't measure the performance impact on the UI yet, but a decorator could be created and perform the storage test only every X minutes (with the last timestamp of execution in the local storage for instance).
Here is a good resource for the error you are running into.
http://www.sitepoint.com/building-web-pages-with-local-storage/#fbid=5fFWRXrnKjZ
Gives some insight that localstorage only has so much room and you can max it out in each browser. Look into removing some data from localstorage to resolve your problem.
Less.js persistently caches content that is #imported. You can use this script to clear content that is cached. Using the script below you can call the function destroyLessCache('/path/to/css/') and it will clear your localStorage of css files that have been cached.
function destroyLessCache(pathToCss) { // e.g. '/css/' or '/stylesheets/'
if (!window.localStorage || !less || less.env !== 'development') {
return;
}
var host = window.location.host;
var protocol = window.location.protocol;
var keyPrefix = protocol + '//' + host + pathToCss;
for (var key in window.localStorage) {
if (key.indexOf(keyPrefix) === 0) {
delete window.localStorage[key];
}
}
}