using express node.js, call a function in a function and exports and require in router and hand in to ejs when rendering in router - node.js

can a function be recognized inside a function when both would be exported?
this is my code
exports.generateUrlWithParam = function(idpUrl,subUrl,param){
var url = generateUrl(idpUrl, subUrl);
if(url == null) {
return null;
}
var paramStr = generateParam(param);
return url + "?" + paramStr;
}
and this function is to be used inside generateUrlWithParam
exports.generateUrl = function(idpUrl, subUrl) {
if((idpUrl == null || ""==idpUrl.trim()) && (subUrl == null || ""==subUrl.trim())) {
return null;
}
let url = idpUrl
if(!idpUrl.endsWith("/")) {
url += "/";
}
url += subUrl;
url = url.replace(/\/+/g, "/");
if(url.startsWith("http:/") && !url.startsWith("http://")) {
url = url.replace(/^http:\//, "http://");
} else if(url.startsWith("https:/") && !url.startsWith("https://")) {
url = url.replace(/^https:\//, "https://");
}
return url;
}
and they will be used in ejs file.
apparently generateUrl is not recognized
i'm using this js file by 'require' in my router file and hand to the ejs file
any ideas would be appreciated in advance thank you.

You can refer this function as var url = exports.generateUrl(idpUrl, subUrl);

Related

How to change the default values when add link Sharepoint 2013

In Add Link page, is it possible to change the default values like title, address, show these links to, by using URL parameters?
According to this, it seems possible in sharepoint2010. Does anyone know whether it works in 2013??
If not, is it possible to add a link by post REST API??
This problem can be solved by the steps below.
Add a custom action. Just follow the steps here.
In my case code is as below
SP.SOD.executeFunc("callout.js", "Callout", function() {
var itemCtx = {};
itemCtx.Templates = {};
itemCtx.BaseViewID = 'Callout';
// Define the list template type
itemCtx.ListTemplateType = 101;
itemCtx.Templates.Footer = function(itemCtx) {
// context, custom action function, show the ECB menu (boolean)
return CalloutRenderFooterTemplate(itemCtx, AddCustomAction, true);
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
});
function AddCustomAction(renderCtx, calloutActionMenu) {
// Add your custom action
calloutActionMenu.addAction(new CalloutAction({
text: "FAVORITE",
// tooltip: 'This is your custom action',
onClickCallback: function() {
CreateCustomNewQuickLink(renderCtx.CurrentItem.FileLeafRef, renderCtx.CurrentItem.FileRef);
}
}));
// Show the default document library actions
CalloutOnPostRenderTemplate(renderCtx, calloutActionMenu);
}
function CreateCustomNewQuickLink(title, url) {
var urlAddress = $(location).attr('protocol') + "//" + $(location).attr('host') + '/_Layouts/quicklinksdialogformTEST.aspx?Mode=Link' +
'&title=' + encodeURIComponent(title) +
'&url=' + encodeURIComponent(url);
ShowNewQuicklinkPopup(urlAddress, PageRefreshOnDialogClose);
}
Create a new add link page which is copied from "quicklinksdialogform.aspx". I add some javascript as below.
$(init)
function init() {
var args = new Object();
args = GetUrlParms();
if (args["title"] != undefined) {
$(".ms-long")[0].value = decodeURIComponent(args["title"]);
}
if (args["url"] != undefined) {
$(".ms-long")[1].value = decodeURIComponent(args["url"]);
}
}
function GetUrlParms() {
var args = new Object();
var query = location.search.substring(1);
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
var pos = pairs[i].indexOf('=');
if (pos == -1) continue;
var argname = pairs[i].substring(0, pos);
var value = pairs[i].substring(pos + 1);
args[argname] = unescape(value);
}
return args;
}
It works like below

NodeJs : Any way to bypass querystring.stringify with empty Object?

I am working currently on a project that requires to send custom GET HTTP requests.
I am using the default querystring builder : the Documentation
const querystring = require('querystring');
The problem is for Object (probably also for empty array) such as
extendTypes={}
is serialiazed as :
extendTypes=
The expected result :
extendTypes={}
or its URI encoded version :
extendTypes%3D%7B%7D
So , how can I ever hope to do that ? If It is impossible with the in-builded module, which one could do what I want.
Here is my full code if you want :
function generateGetRequest(dataMap, url) {
let queryParams = {};
let uriParams = {};
for (let [key, value] of dataMap) {
// if value is an object or an array
if (value instanceof Object || value instanceof Array) {
uriParams[key] = value;
} else {
// param working for superagent
queryParams[key] = value;
}
}
let queryParamsUri = querystring.stringify(uriParams);
console.log(queryParamsUri);
let finalUrl = url + ( (Object.keys(uriParams).length > 0) ? "?" + queryParamsUri : "");
}
I finally found a workaround , if someone wants to know :
let request = require("superagent");
function generateGetRequest(dataMap, url) {
let queryParams = {};
let queryParamsUri = "";
let isFirstParam = true;
for (let [key, value] of dataMap) {
// if value is an object or an array
if (value instanceof Object) {
// Workaround for empty object or array = https://github.com/nodejs/node/issues/12234
queryParamsUri += ((!isFirstParam) ? "&": "") + key + "=" + JSON.stringify(value);
// for next call
isFirstParam = false;
} else {
// param working for superagent
queryParams[key] = value;
}
}
let finalUrl = url + ( (!isFirstParam) ? "?" + queryParamsUri : "");
return request
.get(finalUrl)
.query(queryParams);
}

node js giving "RangeError: Maximum call stack size exceeded" on VPS machine

I am using Phantom JS to load a third party URL. Then there is an node+express server with "phantom" module, which is returning back the htmls from Phantom JS.
The code works perfect in my mac, but when I try to run it in VPS, node is giving
RangeError: Maximum call stack size exceeded
function scrape(url, func){
var phantom = require('phantom');
phantom.create('--load-images=no', function(ph){
return ph.createPage(function(page){
page.set('settings.loadImages', false) ;
return page.open(url, function(status){
//page.injectJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function() {
return page.evaluate((function(){
var scripts = document.getElementsByTagName('script'),
links = document.getElementsByTagName('link'),
images = document.getElementsByTagName('img'),
objects = document.getElementsByTagName('object');
for(i in objects){
if((obj = objects[i]) && obj.data){
if(obj.getAttribute('data') != obj.data){
obj.setAttribute('data', obj.data);
var params = obj.getElementsByTagName('param');
for(var j in params){
if((par = params[j]) && par.value){
console.log(par.name);
if(par.getAttribute('value') != par.value){
par.setAttribute('value', par.value);
}
if(par.name == "allowscriptaccess" ){
par.setAttribute('value', "always");
par.value = "always";
}
}
}
}
}
}
for(i in scripts){
if((script = scripts[i]) && script.src){
if(script.getAttribute('src') != script.src){
script.setAttribute('src', script.src);
}
}
}
for(i in links){
if((link = links[i]) && link.href ){
if(link.getAttribute('href') != link.href){
link.setAttribute('href', link.href);
}
}
}
for(i in images){
if((image = images[i]) && image.src){
if(image.getAttribute('src') != image.src){
image.setAttribute('src', image.src);
}
}
}
var baseTag = document.getElementsByTagName('base');
if(baseTag.length == 0){
var baseTag = '<base id="test" href="'+ document.domain +'" />';
var head = document.getElementsByTagName('head');
head[0].innerHTML = baseTag + head[0].innerHTML;
}
return document.getElementsByTagName('html')[0].outerHTML;
}), function(result){
ph.exit(); (func)(result);
});
//});
});
});
});
}
exports.scrape = scrape;

Redirecting to mobile website using opencms

I have a website developed using OPENCMS. Now we have developed a mobile website. How do i add code or module to opencms so that when user visits from mobile, it will be redirected to mobile website.
Insert at the beginning of one of the pages in the editor.
<?php
function detect_mobile()
{
if(preg_match('/(alcatel|amoi|android|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipad|ipaq|ipod|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic|philips|phone|sagem|sharp|sie-|smartphone|sony|symbian|t-mobile|telus|up\.browser|up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i', $_SERVER['HTTP_USER_AGENT']))
return true;
else
return false;
}
$mobile = detect_mobile();
if($mobile === true)
header('Location: /mobile');
?>
<script type="text/javascript">
var url=***'http://yourmobilesite.com/***';
var host_name=document.location.hostname;
var request_uri=document.location.pathname;
var no_mobile=location.search;
var cookie=document.cookie;
function detect()
{
var ua=navigator.userAgent.toLowerCase();
var devices=['vnd.wap.xhtml+xml','sony','symbian','nokia','samsung','mobile',
'windows ce','epoc','opera mini','nitro','j2me','midp-','cldc-',
'netfront','mot','up.browser','up.link','audiovox','blackberry',
'ericsson','panasonic','philips','sanyo','sharp','sie-',
'portalmmm','blazer','avantgo','danger','palm','series60',
'palmsource','pocketpc','smartphone','rover','ipaq','au-mic',
'alcatel','ericy','vodafone','wap1','wap2','teleca',
'playstation','lge','lg-','iphone','android','htc','dream',
'webos','bolt','nintendo'];
for (var i in devices)
{
if (ua.indexOf(devices[i]) != -1)
{
return true
}
}
}
if (no_mobile!='?nomobile=1' && cookie.indexOf('no_mobile')==-1)
{
is_mobile=detect();
if (is_mobile)
{
window.location = url
}
}
else
{
if (cookie.indexOf('no_mobile') != -1)
{}
else
{
cookie_expires = new Date();
cookie_expires.setTime(cookie_expires.getTime()+60*60*24);
document.cookie = "no_mobile=1; expires="
+ cookie_expires.toGMTString()
+ "; path=/;"
}
}
</script>

Opening tabs in Chrome news reader extension

I'm trying to create a simple chrome extension using the following google RSS reader sample,
http://code.google.com/chrome/extensions/samples.html#597015d3bcce3da693b02314afd607bec4f55291
I can add links in the pop-up window that open tabs, but not from the feeds themselves.
Looping through the items in the feed, grabbing title tags and link tags, I want the title to link the the appropriate sites
var entries = doc.getElementsByTagName('item');
var count = Math.min(entries.length, maxFeedItems);
for (var i = 0; i < count; i++) {
item = entries.item(i);
// Grab the title for the feed item.
var itemTitle = item.getElementsByTagName('title')[0];
if (itemTitle) {
itemTitle = itemTitle.textContent;
} else {
itemTitle = "Unknown title";
}
// Grab the link for this feed item
var itemLink = item.getElementsByTagName('link')[0];
if (itemLink) {
itemLink = itemLink.textContent;
} else {
itemLink = "Unknown link";
}
var title = document.createElement("a");
title.className = "item_title";
title.innerText = itemTitle; //display title in iframe
title.addEventListener("click", titleLink); // should open link when clicking on title, but does not.
}
// -------------------------------------------------------------------
// Show |url| in a new tab.
function showUrl(url) {
// Only allow http and https URLs.
if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
return;
}
chrome.tabs.create({url: url});
}
function moreStories(event) {
showUrl(moreStoriesUrl);
}
function titleLink(event) {
showUrl(itemLink);
}
Any thoughts on why this is not working.
If I replace title.addEventListener("click", titleLink); with title.addEventListener("click", moreStories); each title will link to moreStories, I cannot get each title to link to itemLink.
Thanks
Its a bit hard to answer your question without the whole code, but Ill give it a shot ;)
First up, titleLink() isnt going to work because itemLink isnt known. When you create title (the link) you should of attached it to that...say title.href=itemLink then in tiltleLinks you could access that href with showUrl(event.currentTarget.href)
Also did you fix the error in that example?...if not then change frameLoaded to....
function frameLoaded() {
var links = document.getElementsByTagName("A");
for (i = 0; i < links.length; i++) {
var clssName = links[i].className;
if (clssName != "item_title" && clssName != "open_box") {
links[i].addEventListener("click", showStory);
}
}
window.addEventListener("message", messageHandler);
}
If you still have probs could you attach the whole code so I can see what your doing and Ill give you a hand.
Thank you very much for your help.
code title.href=itemLink and code showUrl(event.currentTarget.href) was exactly what I needed.
For completeness, here is the full code,
<script id="iframe_script">
function reportHeight() {
var msg = JSON.stringify({type:"size", size:document.body.offsetHeight});
parent.postMessage(msg, "*");
}
function frameLoaded() {
var links = document.getElementsByTagName("A");
for (i = 0; i < links.length; i++) {
var class = links[i].className;
if (class != "item_title" && class != "open_box") {
links[i].addEventListener("click", showStory);
}
}
window.addEventListener("message", messageHandler);
}
function showStory(event) {
var href = event.currentTarget.href;
parent.postMessage(JSON.stringify({type:"show", url:href}), "*");
event.preventDefault();
}
function messageHandler(event) {
reportHeight();
}
</script>
<script>
// Feed URL.
var feedUrl = 'http://localhost/newsfeed.xml';
// The XMLHttpRequest object that tries to load and parse the feed.
var req;
function main() {
req = new XMLHttpRequest();
req.onload = handleResponse;
req.onerror = handleError;
req.open("GET", feedUrl, true);
req.send(null);
}
// Handles feed parsing errors.
function handleFeedParsingFailed(error) {
var feed = document.getElementById("feed");
feed.className = "error";
feed.innerText = "Error: " + error;
}
// Handles errors during the XMLHttpRequest.
function handleError() {
handleFeedParsingFailed('Failed to fetch RSS feed.');
}
// Handles parsing the feed data we got back from XMLHttpRequest.
function handleResponse() {
var doc = req.responseXML;
if (!doc) {
handleFeedParsingFailed("Not a valid feed.");
return;
}
buildPreview(doc);
}
// The maximum number of feed items to show in the preview.
var maxFeedItems = 10;
// Where the more stories link should navigate to.
var moreStoriesUrl;
function buildPreview(doc) {
// Get the link to the feed source.
var link = doc.getElementsByTagName("link");
var parentTag = link[0].parentNode.tagName;
if (parentTag != "item" && parentTag != "entry") {
moreStoriesUrl = link[0].textContent;
}
// Setup the title image.
var images = doc.getElementsByTagName("image");
var titleImg;
if (images.length != 0) {
var urls = images[0].getElementsByTagName("url");
if (urls.length != 0) {
titleImg = urls[0].textContent;
}
}
var img = document.getElementById("title");
// Listen for mouse and key events
if (titleImg) {
img.src = titleImg;
if (moreStoriesUrl) {
document.getElementById("title_a").addEventListener("click",moreStories);
document.getElementById("title_a").addEventListener("keydown",
function(event) {
if (event.keyCode == 13) {
moreStories(event);
}});
}
} else {
img.style.display = "none";
}
// Construct the iframe's HTML.
var iframe_src = "<!doctype html><html><head><script>" +
document.getElementById("iframe_script").textContent + "<" +
"/script></head><body onload='frameLoaded();' " +
"style='padding:0px;margin:0px;'>";
var feed = document.getElementById("feed");
// Set ARIA role indicating the feed element has a tree structure
feed.setAttribute("role", "tree");
var entries = doc.getElementsByTagName('item');
var count = Math.min(entries.length, maxFeedItems);
for (var i = 0; i < count; i++) {
item = entries.item(i);
// Grab the title for the feed item.
var itemTitle = item.getElementsByTagName('title')[0];
if (itemTitle) {
itemTitle = itemTitle.textContent;
} else {
itemTitle = "Unknown title";
}
// Grab the link for the feed item.
var itemLink = item.getElementsByTagName('link')[0];
if (itemLink) {
itemLink = itemLink.textContent;
} else {
itemLink = "Unknown link";
}
var item = document.createElement("div");
var title = document.createElement("a");
title.innerText = itemTitle; //display title in iframe
title.href=itemLink;
title.addEventListener("click", titleLink);
item.appendChild(title);
feed.appendChild(item);
}
if (moreStoriesUrl) {
var more = document.createElement("a");
more.className = "more";
more.innerText = "***Site Main Page*** \u00BB";
more.tabIndex = 0;
more.addEventListener("click", moreStories);
more.addEventListener("keydown", function(event) {
if (event.keyCode == 13) {
moreStories(event);
}});
feed.appendChild(more);
}
}
// -------------------------------------------------------------------
// Show |url| in a new tab.
function showUrl(url) {
// Only allow http and https URLs.
if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
return;
}
chrome.tabs.create({url: url});
}
// -------------------------------------------------------------------
function moreStories(event) {
showUrl(moreStoriesUrl);
}
function titleLink(event) {
showUrl(event.currentTarget.href);
}
function keyHandlerShowDesc(event) {
// Display content under heading when spacebar or right-arrow pressed
// Hide content when spacebar pressed again or left-arrow pressed
// Move to next heading when down-arrow pressed
// Move to previous heading when up-arrow pressed
if (event.keyCode == 32) {
showDesc(event);
} else if ((this.parentNode.className == "item opened") &&
(event.keyCode == 37)) {
showDesc(event);
} else if ((this.parentNode.className == "item") && (event.keyCode == 39)) {
showDesc(event);
} else if (event.keyCode == 40) {
if (this.parentNode.nextSibling) {
this.parentNode.nextSibling.children[1].focus();
}
} else if (event.keyCode == 38) {
if (this.parentNode.previousSibling) {
this.parentNode.previousSibling.children[1].focus();
}
}
}
function showDesc(event) {
var item = event.currentTarget.parentNode;
var items = document.getElementsByClassName("item");
for (var i = 0; i < items.length; i++) {
var iframe = items[i].getElementsByClassName("item_desc")[0];
if (items[i] == item && items[i].className == "item") {
items[i].className = "item opened";
iframe.contentWindow.postMessage("reportHeight", "*");
// Set the ARIA state indicating the tree item is currently expanded.
items[i].getElementsByClassName("item_title")[0].
setAttribute("aria-expanded", "true");
iframe.tabIndex = 0;
} else {
items[i].className = "item";
iframe.style.height = "0px";
// Set the ARIA state indicating the tree item is currently collapsed.
items[i].getElementsByClassName("item_title")[0].
setAttribute("aria-expanded", "false");
iframe.tabIndex = -1;
}
}
}
function iframeMessageHandler(e) {
// Only listen to messages from one of our own iframes.
var iframes = document.getElementsByTagName("IFRAME");
for (var i = 0; i < iframes.length; i++) {
if (iframes[i].contentWindow == e.source) {
var msg = JSON.parse(e.data);
if (msg) {
if (msg.type == "size") {
iframes[i].style.height = msg.size + "px";
}
else if (msg.type == "show") {
var url = msg.url;
if (url.indexOf("http://localhost/index.html") == 0) {
// If the URL is a redirect URL, strip of the destination and go to
// that directly. This is necessary because the Google news
// redirector blocks use of the redirects in this case.
var index = url.indexOf("&url=");
if (index >= 0) {
url = url.substring(index + 5);
index = url.indexOf("&");
if (index >= 0)
url = url.substring(0, index);
}
}
showUrl(url);
}
}
return;
}
}
}
window.addEventListener("message", iframeMessageHandler);
</script>
Thanks again for the help.
-Mike

Resources