How do you clone a cheerio object - cheerio

I've got a cheerio object:
const $ = cheerio.load('<span class="layer-chunk"></span>')
This is a simple example it is far more complex.
I need to clone it so that I can do different things with it without actually effecting it.
This is what I've got so far:
const clone = $ => {
const strHtml = $('body').html()
return cheerio.load(strHtml)
}
const myClone = clone($)
But I am sure this is not a cheap op. There is a clone method in the docs but I cannot get it to work. I've tried this:
const myClone = $.root().clone()
But no cigar. Anyone know best practice for cloning a cheerio object? thanks

You can always just do:
cheerio.load($.html())

As shown in the documentation all you need to do is
const $ = cheerio.load('<div id="fruits">This is <em>content</em>.</div>')
const moreFruit = $('#fruits').clone()
or you can check cloneDom on the this link
Create a deep copy of the given DOM structure by first rendering it to
a * string and then parsing the resultant markup.
Thanks

I think in order to actually use the clone you have to do it like this:
cheerio('.layer-chunk', clone).text('something')
^^^^^

Related

Can't parse <content:encoded> from RSS

This is what RSS looks like: https://reddit.0qz.fun/r/dankmemes/top.json
My script perfectly parses "title", "description" and other items tags from the RSS. But it doesn't parse "content:encoded".
I tried this:
item.getChild("content:encoded").getText();
And this:
item.getChild("encoded").getText();
And this (found on Stackoverflow):
item.getChild("http://purl.org/rss/1.0/modules/content/","encoded").getText();
But nothing works... Could you help me?
The namespace is important for the getChild and similar methods to parse the content successfully.
Your third example is close, but you have the parameter order backwards, and you need to use the XmlService.getNamespace method, not a raw string. (The signature is getChild(string, namespace), not getChild(string, string).)
This one is tricky as the namespace should be included for some of the elements, and not for others. I am not an XML expert, so I don't know if this is expected behavior or not. The minimal example script below does find and log the text of the <content:encoded> elements using getChild, but I was only able to figure out when to include or exclude the namespace through trial and error. (If anyone has further info on why this is, please let me know in the comments.)
function logContentEncoded() {
const result = UrlFetchApp.fetch("https://reddit.0qz.fun/r/dankmemes/top.json");
const document = XmlService.parse(result.getContentText());
const root = document.getRootElement();
const namespace = XmlService.getNamespace("http://purl.org/rss/1.0/modules/content/");
const channel = root.getChild("channel"); // fails if namespace is included
const item = channel.getChild("item"); // fails if namespace is included
const encoded = item.getChild("encoded", namespace); // fails if namespace is EXCLUDED
console.log(encoded.getText());
}
Adding this library to the project: 1Mc8BthYthXx6CoIz90-JiSzSafVnT6U3t0z_W3hLTAX5ek4w0G_EIrNw
You can scrape the page. With this code, i.e., You can get the first content of <content:encoded> tags.
function getDataFromJson() {
var url = "https://reddit.0qz.fun/r/dankmemes/top.json";
var fromText = '<content:encoded>';
var toText = '</content:encoded>';
var content = UrlFetchApp.fetch(url).getContentText();
var scraped = Parser
.data(content)
.from(fromText)
.to(toText)
.build();
Logger.log(scraped);
return scraped;
}

Access the query string in VueJS

I've just started using VueJS and I'm really liking it! :) I would like to save the values in the querystring to a VueJS variable - this is something super simple in handlebars + express, but seems more difficult in Vue.
Essentially I am looking for something similar to -
http://localhost:8080/?url=http%3A%2F%2Fwww.fake.co.uk&device=all
const app = new Vue({
...
data: {
url: req.body.url,
device: req.body.device
}
...
});
Google seemed to point me to vue-router, but I'm not sure if that's really what I need/how to use it. I'm currently using express to handle my backend logic/routes.
Thanks,
Ollie
You can either to put all your parameters in hash of the url, e.g.:
window.location.hash='your data here you will have to parse to'
and it will change your url - the part after #
Or if you insist to put them as query parameters (what's going after ?) using one of the solutions from Change URL parameters
You can use URLSearchParams and this polyfill to ensure that it will work on most web browsers.
// Assuming "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
Source:
https://davidwalsh.name/query-string-javascript
URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
https://github.com/WebReflection/url-search-params/blob/master/build/url-search-params.js
See also:
https://stackoverflow.com/a/12151322/194717

Gulp: How to set users home directory in Gulp destination?

Is there a way I can read %USERPROFILE% directory in Gulp task and use it for destination to pipe to?
gulp.task('push-my-repos', function () {
var baseDir = '../Bower-Learning-1';
var dest = 'C://Users//user-1//AppData/Local//MY//Bower//Repos//**';
var src = ['../**/*.*', '!./**/', '!../*.*'];
console.log("%USERPROFILE%");
return gulp.src(src, { base: baseDir})
.pipe(gulp.dest(dest))
});
In this sample task I want to pick "dest" dynamically instead of hard coding so that my colleagues can run this task without changing it.
As stated in the accepted answer, the home directory can be accessed from
process.env.HOME
I made it work with the help of node environment variables.

as3 get vars from url

I found this post and I used the code almost exactly to how they suggested. It doesn't work. Do I need to add something in the php? What am I doing wrong?
Am I missing an import?
Thanks
Here is my code:
my php link is: www.mySite.com/example.php?id=true
var search:String = ExternalInterface.call("window.location.search");
var vars:URLVariables = new URLVariables(search);
if(vars.id)
{
/// Do something
}
Found answer here but doesn't work for me.
How to get/obtain Variables from URL in Flash AS3
You forgot to get rid of the page address:
var search:String = "www.mySite.com/example.php?id=true";
var vars:URLVariables = new URLVariables(search.substr(search.indexOf("?")+1));
if(vars.id) trace(vars.id);
Provided that you are sure that the address contains ? and actual variables you are looking for.

Node.js : How to embed Node.js into HTML?

In a php file I can do:
<p><?php echo "hello!";?></p>
Is there a way to do this in node, if yes what's the logic for it?
I have an idea how could this be done:
Use an identifier markup for node in the HTML file like: <node>code</node>
Load & Parse HTML file in Node
Grab node markup from the HTML file and run it
But I'm not sure if this is the best way or even if it works :)
Please note I want to learn node.js, so express and other libraries and modules are not answers for me, because I want to know the logic of the process.
What your describing / asking for a node.js preprocessor. It does exist but it's considered harmful.
A better solution would be to use views used in express. Take a look at the screencasts.
If you must do everything from scratch then you can write a micro templating engine.
function render(_view, data) {
var view = render.views[view];
for (var key in data) {
var value = data[key];
view.replace("{{" + key + "}}", value);
}
return view;
}
render.views = {
"someView": "<p>{{foo}}</p>"
};
http.createServer(function(req, res) {
res.end(render("someView", {
"foo": "bar"
}));
});
There are good reasons why mixing php/asp/js code directly with HTML is bad. It does not promote seperation of concerns and leads to spaghetti code. The standard method these days is templating engines like the one above.
Want to learn more about micro templating? Read the article by J. Resig.
You can try using JooDee, a node webserver which allows you to embed serverside javascript in your web pages. If you are familiar with Node and PHP/ASP, it is a breeze to create pages. Here's a sample of what a page looks like below:
<!DOCTYPE html>
<html>
<: //server side code in here
var os = require('os');
var hostname = os.hostname();
:>
<body>
<div>Your hostname is <::hostname:></div>
</body>
</html>
Using JooDee also lets you expose server javascript vars to the client with no effort by attaching attributes to the 'Client' object server side, and accessing the generated 'Client' object in your client side javascript.
https://github.com/BigIroh/JooDee
Use a template engine. From terminal
npm install ejs
In code:
var ejs = require('ejs');
var options = {
locals: {
foo: function() { return "bar"; }
}
};
var template = "<p><%= foo() %></p>";
console.log(ejs.render(template, options));