How to acess JSON object inside a script tag? - node.js

I have an API call to google directions API and then i
am trying to save that JSON response in a variable called as lat through this code
app.post("/from", function(req,res) {
from = req.body.from;
to = req.body.to;
const url = "https://maps.googleapis.com/maps/api/directions/json?origin="+ from + "&destination=" + to + "&key=AIzaSyDYRICW4Bm4donS0-9LCp_h0nlsyWvEuGY";
console.log(from,to);
https.get(url, function(response) {
console.log(response.statusCode);
var buffers = []
response
.on('data', function(data) {
buffers.push(data)
})
.on('end', function() {
lat = JSON.parse(Buffer.concat(buffers).toString());
console.log(lat);
Now, inside my ejs file i want to pass this response inside a script tag in order to render a map.
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 12
});
var routes = directionsServiceResponse.routes;
console.log("legs " + routes[0].legs.length);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < routes[0].legs.length; i++) {
var leg = routes[0].legs[i];
for (var j = 0; j < leg.steps.length; j++) {
var step = leg.steps[j];
var color = "black";
if (step.travel_mode == "WALKING")
color = "red";
else if (step.travel_mode == "TRANSIT")
color = "green";
var polyline = new google.maps.Polyline({
path: google.maps.geometry.encoding.decodePath(step.polyline.points),
map: map,
strokeColor: color
});
google.maps.event.addListener(polyline, 'click', function(evt) {
infowindow.setContent("leg " + i + " polyline " + j)
})
for (var ii = 0; ii < polyline.getPath().getLength(); ii++) {
bounds.extend(polyline.getPath().getAt(ii));
}
}
}
map.fitBounds(bounds);
}
var directionsServiceResponse = <%= var %>
</script>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=key&callback=initMap&libraries=geometry" async defer></script>
i have tried passing that variable as a ejs variable but its not working

Related

How do I add an inline HTML field to a Suitelet to hold html markup?

Edit: code updated
I am trying to follow along with this blogpost which shows how to create a Suitelet which has a formatted table https://followingnetsuite.com/2020/10/16/skip-freemarker-by-delivering-saved-search-results-in-a-suitelet/
The blog post references adding a inline html field to hold the html mark up. I have tried to add this to the code though I know I am way off:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search", "N/ui/serverWidget"], function (search, ui) {
function onRequest(context) {
if (context.request.method === "GET") {
var form = ui.createForm({ title: "freemarker test" });
function getIssues() {
var issues = new Array();
var mySearch = search.load({
id: "customsearchcustomerallview",
});
var myPages = mySearch.runPaged({ pageSize: 1000 });
for (var i = 0; i < myPages.pageRanges.length; i++) {
var myPage = myPages.fetch({ index: i });
myPage.data.forEach(function (result) {
var issue = {};
mySearch.columns.forEach(function (col, index) {
issue["column_" + index] = {
label: col.label,
text: result.getText(col),
value: result.getValue(col),
};
});
issues.push(issue);
});
}
return issues;
}
function formatIssues(issues) {
var html = new Array();
html.push('<table class="RPT">');
html.push("<thead>");
if (issues.length > 0) {
var issue = issues[0];
html.push("<tr>");
for (var i = 0; i < 20; i++) {
if (issue.hasOwnProperty("column_" + i)) {
var sortType = isNaN(
issue["column_" + i].text || issue["column_" + i].value
)
? "string"
: "float";
html.push(
'<th data-sort="' +
sortType +
'">' +
issue["column_" + i].label +
"</th>"
);
}
}
html.push("</tr>");
}
html.push("</thead>");
html.push("<tbody>");
issues.forEach(function (issue) {
html.push("<tr>");
for (var i = 0; i < 20; i++) {
if (issue.hasOwnProperty("column_" + i)) {
var vAlign = isNaN(
issue["column_" + i].text || issue["column_" + i].value
)
? "left"
: "right";
html.push(
'<td align="' +
vAlign +
'">' +
(issue["column_" + i].text || issue["column_" + i].value) +
"</td>"
);
} else {
break;
}
}
html.push("</tr>");
});
html.push("</tbody>");
html.push("</table>");
return html.join("\n");
}
var htmlField = html.addField({
id: "custpage_html",
label: "html",
type: ui.FieldType.INLINEHTML,
});
htmlField.defaultValue = formatIssues(getIssues());
context.response.writePage(form);
}
}
return {
onRequest: onRequest,
};
});
I can't see the correct way to add this though. Where do I add the inline html field?
For a Suitelet, does the 'context.response.writePage(form)' need to be at the end of the rest of the code? (i.e. after the function that relates to the html markup?
Thanks
Add your HTML via the defaultValue property of the Inline HTML Field.
Structure your script as follows:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search", "N/ui/serverWidget"], function (search, ui) {
function onRequest(context) {
if (context.request.method === "GET") {
var form = ui.createForm({ title: "freemarker test" });
function getIssues() {
var issues = [];
return issues;
}
function formatIssues(issues) {
var html = [];
return html.join("\n");
}
var htmlField = form.addField({
id: "custpage_html",
label: "html",
type: ui.FieldType.INLINEHTML,
});
htmlField.defaultValue = formatIssues(getIssues());
context.response.writePage(form);
}
}
return {
onRequest: onRequest,
};
});
or, if you don't need any other NetSuite Form elements:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/search"], function (search) {
function onRequest(context) {
if (context.request.method === "GET") {
function getIssues() {
var issues = [];
return issues;
}
function formatIssues(issues) {
var html = [];
return html.join("\n");
}
context.response.write(formatIssues(getIssues()));
}
}
return {
onRequest: onRequest,
};
});
You add the field to your form by calling Form.addField from your form object:
var field = html.addField({
id : 'custpage_inlineresults',
type : serverWidget.FieldType.INLINEHTML,
label : 'Search Results'
});
See SuiteAnswer #43669.

Apply the same JavaScript on multiple div scroll

I found this simple horizontal scroll :
http://jsfiddle.net/Lpjj3n1e/
Its working fine, but if I duplicate the horizontal scroll, only the first scroll function well.
What can I do to the JavaScript to be applied on 2, 3 or any variable number of generated scrolls ?
$(function() {
var print = function(msg) {
alert(msg);
};
var setInvisible = function(elem) {
elem.css('visibility', 'hidden');
};
var setVisible = function(elem) {
elem.css('visibility', 'visible');
};
var elem = $("#elem");
var items = elem.children();
// Inserting Buttons
elem.prepend('<div id="right-button" style="visibility: hidden;"><</div>');
elem.append(' <div id="left-button">></div>');
// Inserting Inner
items.wrapAll('<div id="inner" />');
// Inserting Outer
debugger;
elem.find('#inner').wrap('<div id="outer"/>');
var outer = $('#outer');
var updateUI = function() {
var maxWidth = outer.outerWidth(true);
var actualWidth = 0;
$.each($('#inner >'), function(i, item) {
actualWidth += $(item).outerWidth(true);
});
if (actualWidth <= maxWidth) {
setVisible($('#left-button'));
}
};
updateUI();
$('#right-button').click(function() {
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos - 200
}, 800, function() {
debugger;
if ($('#outer').scrollLeft() <= 0) {
setInvisible($('#right-button'));
}
});
});
$('#left-button').click(function() {
setVisible($('#right-button'));
var leftPos = outer.scrollLeft();
outer.animate({
scrollLeft: leftPos + 200
}, 800);
});
$(window).resize(function() {
updateUI();
});
});

how to create multiple it statements with in one For loop protractor

I have multiple it statements in one describe {}. In one it statement I am reading data from excel and doing for loop to execute test scripts for number of users in the sheet. I need to create page model and so for each page thinking on creating one it statement. How can we do that. Here is my actual script
var login = require('./login');
var utility = require('./utility');
var exRead = require('./readExcel');
describe('MSIX Smoke', function () {
var userList = [];
beforeAll(function(done) {
browser.get('https://url'); //Dev url
expect(browser.getTitle()).toEqual('test');
exRead().then(function(excelData) {
userList = prepData(excelData);
done();
});
});
it('should login users', function() {
var loopCount = userList.length
loopCount=1;
for (var i = 0; i<loopCount; i++) {
var data = userList[i];
loginScript(data[0], data[1], data[2]);
login.clickSignOut();
}
})
it('search for a student', function () {
console.log(data[3]);
});
it ('click on my account', function () {
//some code
})
});
function prepData(data) {
var formattedData = [];
var counter = data.length / 5;
for (var i = 0; i < counter; i++) {
formattedData.push(data.splice(0,5))
}
return formattedData;
}
function loginScript(username, password, userType) {
var loginName = element(by.css('.nameP'));
console.log(username, password);
login.fillUsername(username);
login.fillPassword(password);
login.clickSignup();
login.clickPrivacy();
console.log("User " + username + " with user type "+userType+" logged in successfully");
loginName.isPresent;
utility.getStringText("Logged in user name is: ", loginName);
return loginName;
};
Give code examples with two approaches:
describe('xxx', function() {
browser.get('https://www.npmjs.com');
var datas = [1, 2, 3];
// Option 1, use for loop and javascript closure
for (var i = 0, len = datas.length; i < len; i++) {
(function(i) {
return it('yyy ' + i, function() {
console.log('data[' + i + '] = ' + datas[i]);
browser.getTitle().then(function(title) {
console.log('title[' + i + '] = ' + title);
});
});
})(i);
}
// option 2, use Array.forEach()
datas.forEach(function(data, i) {
it('yyy ' + i, function() {
console.log('data[' + i + '] = ' + data);
browser.getTitle().then(function(title) {
console.log('title[' + i + '] = ' + title);
});
});
})
});

NodeJS await request returns body instead of function result

I want to console.log(price) print the return value of the function wraped after the '=>', but I'm printing the body of the request.
"use strict";
const request = require('request-promise');
const PromedioPonderado = require('../PromedioPonderado.js');
var exports = module.exports = {};
exports.GetPrices = async function(){
var price = await request('https://www.okex.com/api/v1/depth.do?symbol=btc_usdt', { json: true }, (err, res, body) => {
if (err) { return console.log(err); }
var promedio = new PromedioPonderado();
var bids = body.bids;
for (var i = 0, len = bids.length; i < len; i++) {
var row = bids[i];
var bid = {Price: row[0], Amount: row[1]}
promedio.bid(bid);
}
var asks = body.asks;
for (var i = 0, len = asks.length; i < len; i++) {
var row = asks[i];
var ask = {Price: row[0], Amount: row[1]}
promedio.ask(ask);
}
var askReturn = promedio.askAverage(); //sync function
var bidReturn = promedio.bidAverage(); // sync function
console.log(askReturn)
return {Ask: askReturn, Bid: bidReturn}; //I want to return this value
});
console.log(price);
}
This is PromedioPonderado.js, just in case
"use strict";
class PromedioPonderado {
constructor() {
this._bid = [];
this._ask = [];
}
bid(bid) {
this._bid.push(bid);
}
ask(ask){
this._ask.push(ask);
}
bidAverage(){
var totalAmount = 0;
var i = 0;
var average = 0;
while(totalAmount < 10){
totalAmount = totalAmount + this._bid[i].Amount;
average = average + (this._bid[i].Price * this._bid[i].Amount);
i++;
}
average = average / (totalAmount);
return average.toFixed(2);
}
askAverage(){
var totalAmount = 0;
var i = 0;
var average = 0;
while(totalAmount < 10){
totalAmount = totalAmount + this._ask[i].Amount;
average = average + (this._ask[i].Price * this._ask[i].Amount);
i++;
}
average = average / (totalAmount);
return average.toFixed(2);
}
}
module.exports = PromedioPonderado;
var body = await request('https://www.okex.com/api/v1/depth.do?symbol=btc_usdt', { json: true }
and then you can use the response from the request.
exports.GetPrices = async function(){
var price = await new Promise((resolve, reject) => {
request('https://www.okex.com/api/v1/depth.do?symbol=btc_usdt', { json: true }, (err, res, body) => {
if (err) { reject(err); }
var promedio = new PromedioPonderado();
var bids = body.bids;
for (var i = 0, len = bids.length; i < len; i++) {
var row = bids[i];
var bid = {Price: row[0], Amount: row[1]}
promedio.bid(bid);
}
var asks = body.asks;
for (var i = 0, len = asks.length; i < len; i++) {
var row = asks[i];
var ask = {Price: row[0], Amount: row[1]}
promedio.ask(ask);
}
var askReturn = promedio.askAverage(); //sync function
var bidReturn = promedio.bidAverage(); // sync function
console.log(askReturn)
resolve({Ask: askReturn, Bid: bidReturn}); //I want to return this value
});
})
console.log(price);
}

how to get the result in nodejs server?

now, help me, I try to post data with ajax to nodejs server.
and server accept the postdata. and now i use http.get to request www.baidu.com, and want to get the html , at last return the html to front.but is error
front ajax
$("#subbtn").click(function(){
var keywords = $("#kw").val();
var target = $("#result");
if (!keywords){
target.html("<font color='#FF0000'>please key words</font>");
}
var keyArr = keywords.replace(/\,+/g, ",").split("\,");
for (var i = 0; i < keyArr.length; i++){
$.ajax({
type: "POST",
url: "http://127.0.0.1:10088",
data : { kw : keyArr[i]},
dataType: "json",
cache: false,
timeout: 5000,
success: function(data) {
alert(data.rank);return false;
// $("#result").append(data.num);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
}
});
and the server.js
// Nodejs部分,主要作用是接收前端关键词,抓取百度知道页面。返回页面给前端
var http = require('http');
var cheerio = require('cheerio');
var iconv = require('iconv-lite');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html', 'Access-Control-Allow-Origin' : '*' });
var postData = "";
var ret = 0;
req.setEncoding('utf-8');
req.addListener('data', function(chunk){
postData += chunk;
});
req.addListener('end', function(){
var value = postData.replace(/kw=/, ''), result = 0;
doRequest(value, 0);
});
res.end('{"rank":'+result+'}');
}).listen(10088);
/**
* GET请求Baidu
* #param kw 关键词
* #param page
*/
var doRequest = function(kw, page){
page = page * 10;
var options = {
host: 'zhidao.baidu.com',
port: 80,
path: '/search?word='+kw+'&pn='+page
};
http.get(options, function(res) {
var buffers = [], size = 0;
res.on('data', function(buffer) {
buffers.push(buffer);
size += buffer.length;
});
res.on('end', function() {
var buffer = new Buffer(size), pos = 0;
for(var i = 0, l = buffers.length; i < l; i++) {
buffers[i].copy(buffer, pos);
pos += buffers[i].length;
}
var gbk_buffer = iconv.decode(buffer,'GBK');
$ = cheerio.load(gbk_buffer.toString());
// 获取页面前三个的优质回答
var target = "DARRY RING";
var isBreak = false;
var htmlTop = $("#cluster-items").find(".con-all").slice(0, 3);
htmlTop.each(function(){
var tContent = $(this).text().replace(/\s+/g, "");
tContent = tContent.toLowerCase();
if (tContent.indexOf("darryring") > 0 ){ // 当找到DY的时候,退出循环
isBreak = true;
return false;
}
});
if (isBreak == true){
return {keyword : kw, score : 1};
}
var html = $("#wgt-list").find("dd.answer");
var n = 0;
html.each(function(i, elem){
var content = $(this).text().replace(/\s+/g, "");
content = content.toLowerCase();
if (content.indexOf("darryring") > 0 && n <= html.length ){ // 当找到DY的时候,退出循环
n = i + 1;
return false;
}
});
if(n == 0){
page++;
if (page < 5){
doRequest(kw, page);
}else{
return {keyword : kw, score : 9999};
}
}else{
var num = page + n;
return {keyword : kw, score : num};
}
});
res.on('error', function(e){
console.log("Got error: " + e.message);
})
})
}
Parsing POST data can be tricky business. I recommend using a module to help you out. Formaline has all the bells and whistles you'll need or poor-form is a lighter weight version.

Resources