Display image using Nodejs only - javascript

I am trying to display an image by only using Node js. I have been searching for a way to do this, but the only examples that I can find involve HTML and ID's within the HTML which I do not want to use. Sorry I do not have any code to go along with my question, but is there a way to avoid all HTML and just use Node js or a specific node js module to store the image in a variable which would later be used to display the image?

store the image in a variable which would later be used to display the image
You can achieve this by having NodeJS print you the Data URI of the image. It will be a rather large block of string, so quite cumbersome, but certainly will let you fetch an image from NodeJS without using a web browser/HTML.
You can also launch an arbitrary image viewer of your choice by having NodeJS launch a child process.

Related

PHP and React.js - Best way to store a <svg> element. And read/return/fetch for both languages

Background information##
I'm working on a Wordpress Gutenberg project. And as you might know, Gutenberg uses React on the backend. But PHP on the frontend. (if can't store it pre-rendered.)
First I stored the <svg> HTML elements inside the post content. But after 3 SVG images, it gets too big to store for MySQL. So, now I can't store the Post pre-rendered in the backend I just have to get it dynamically each page load with PHP.
The question
Moving on the question itself. Is there a way to store an HTML <svg> element (with CSS animations) to an external file that both React and PHP can load/fetch?
Thoughts
at first (with react) I had stored it in a .jsxfiletype. Exported it as a const returning a multi-line string.
I thought of placing it within a .JSON filetype. But then I would have to JSON.stringify() it first to escape the characters. But that would result in a human unfriendly way to edit it.
Saving it an SVG won't help, since it's animated.
I could translate all JSX constants containing all the svgs to a PHP function. But that would make it less flexible if I decide to go back to React.
Any help or pointers are very welcome

Get data from another HTML page

I am making an on-line shop for selling magazines, and I need to show the image of the magazine. For that, I would like to show the same image that is shown in the website of the company that distributes the magazines.
For that, it would be easy with an absolute path, like this:
<img src="http://www.remotewebsite.com/image.jpg" />
But, it is not possible in my case, because the name of the image changes everytime there is a new magazine.
In Javascript, it is possible to get the path of an image with this code:
var strImage = document.getElementById('Image').src;
But, is it possible to use something similar to get the path of an image if it is in another HTML page?
Assuming that you know how to find the correct image in the magazine website's DOM (otherwise, forget it):
the magazine website must explicitly allow clients showing your website to fetch their content by enabling CORS
you fetch their HTML -> gets you a stream of text
parse it with DOMParser -> gets you a Document
using your knowledge or their layout (or good heuristics, if you're feeling lucky), use regular DOM navigation to find the image and get its src attribute
I'm not going to detail any of those steps (there are already lots of SO answers around), especially since you haven't described a specific issue you may have with the technical part.
You can, but it is inefficient. You would have to do a request to load all the HTML of that other page and then in that HTML find the image you are looking for.
It can be achieved (using XMLHttpRequest or fetch), but I would maybe try to find a more efficient way.
What you are asking for is technically possible, and other answers have already gone into the details about how you could accomplish this.
What I'd like to go over in this answer is how you probably should architect this given the requirements that you described. Keep in mind that what I am describing is one way to do this, there are certainly other correct methods as well.
Create a database on the server where your app will live. A simple MySQL DB will work, but you could use anything. Create a table called magazine, with a column url. Your code would pull the url from this DB. Whenever the magazine URL changes, just update the DB and the code itself won't need to be changed.
Your front-end code needs some sort of way to access the DB. One possible solution is a REST API. This code would query the DB for the latest values (in your case magazine URLs), and make them accessible to your web page. This could be done in a myriad of different languages/frameworks, here's a good tutorial on doing something like this in Node.js and express (which is what I'd personally use).
Finally, your front-end code needs to call your REST API to get the updated URLs. This needs to be done with some kind of JavaScript based language. jQuery would make this really easy, something like this:
$(document).ready(function() {
$.Get("http://uri_to_your_rest_api", function(data) {
$("#myImage").attr("scr", data.url);
}
});
Assuming you had HTML like this:
<img id="myImage" src="">
And there you go - You have a webpage that pulls the image sources dynamically from your database.
Now if you're just dipping your toes into web development, this may seem a bit overwhelming. But I promise you, in the long run it'll be easier then trying to parse code from an HTML page :)

Load Random Image From Directory on Page Load Without a Listed Array of File Names

I've done some looking around on the site and every time I pull up a solution to this problem, one of the requirements is to have a naming convention and a list of every image to pull from the directory (example: image1.jpg, image2.jpg, etc.) All of the file names are different and there are thousands of them to pick from (so listing each one as a random opportunity in an array is not going to work).
I typically use CMS services and I'm writing this webpage from scratch in Notepad in an attempt to better my coding skills... and I'm not sure where to begin. I'm decent with HTML and CSS, but j Query and JavaScript are not my friends haha.
Thank you for any help! (Even if it's just pointing me to a tutorial or a solution I could not find!!!)
Are all file names image1 image2 image3 etc? Then you could try to generate a random number, create a new img element and have it's source pointing to image+randomnumber.jpg and append it to the DOM
One of the main problems your facing here is about your thinking when it comes to how content is delivered, in a standalone static website you do not have access to the file system. This means that if we want to query things outside of the browsers context we are not allowed, obviously without being able to access directories we can not generate a list of file names which can be loaded.
If your wondering why we can't access the file system directly from say the JavaScript it's because of the sandbox that most modern browsers live in, otherwise people could attack your native directories from the front end languages. Your question is interesting as electron removes this sandboxing in a sophisticated esk manner, which is necessary as it's used for building desktop apps with chromium.
These days the most obvious solution would be to use some form of back end language and to create a web server that has direct access to the native directories around it. Node, PhP, GoLang and many other populatr backend languages can parse a directory of files and then interpolate those into the frontend code which is the most common method.
The other popular method at the moment is to create API's which is just a fancy web server with a queryable end point that then executes code against our web server and provides back a list of such items. You could then for instance take the items and then print those out using javascript.
Reference directories method in php:
http://php.net/manual/en/ref.dir.php
List contents of directory in nodejs:
https://code-maven.com/list-content-of-directory-with-nodejs
The best place to really start with the easiest route to understand more would be to start a backend language in either node or php, with php being the simpler of the two.
https://www.w3schools.com/php/
First you need to get your file list from server side. then you can use a code like following:
var imageList = //your image list as an array of urls;
var imageNumber = Math.random() * imageList.length; //gives you a random number in the range of imageList's size
var imageToLoad = new Image();
imageToLoad.addEventListener("load", function(){
console.log( "image is loading" );
$('#my-container').append(this); //in this case this will return image dom
});
imageToLoad.src = imageList[imageNumber];
this will add image to a container with id 'my-container' its just an example you can do anything you want using 'this'
So after much help and guidance from the community, I have figured out the answer! To clarify my process in extreme detail, here is what I did to achieve the desired outcome:
Create the page as a .php file instead of a .html file (in my case, index.php). If you are using notepad to create the file, make sure you change the file extension to .php, the encoding to UTF-8, and save file type as "All Files". As I understand it, PHP can pick the file at random but cannot pass this info to a static HTML page.
Place this block of code into the webpage where the image should show. Currently, it is set up to reference a folder named, "images" out of the root directory (aka mysite.com/images/). This can be changed by modifying the text between the apostrophes after $imagesDir. All other html markup on the page will work correctly if it is outside of the php code block.
Code Block:
<?php
$imagesDir = 'images/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
echo "<img src='$randomImage'>";
?>
Thank you #bardizba for the code! Although there may be less resource intensive ways to write this, my situation was a bit different because the file names in the directory did not follow a naming convention and there was a mix of file types (jpg, gif, etc.)
Thanks again to everyone that helped me out!

Converting an XML file into an object

I'm trying to use the Planetside 2 database to create a simple application for educational purposes. However, I'm stuck. I need to convert an XML file to a Javascript object so i can use the data easily and display it on my app. Problem is, the file is a link, i suppose. I tried it just like you would with a file located on the same server/PC however that doesnt work.
This is the link:
http://census.daybreakgames.com/xml/get/ps2:v2/character/?name.first_lower=litebrite
My question is, How do i convert/turn this onto an object usable in Javascript? (I have absolute no experience in javascript, hence the reason i'm not using the JSON verion of the file)
Thanks

Including Information in HTML for Javascript to Consume?

I'm am building a web app with app engine (java) and GWT, although I think my problem is moreso a general javascript question.
In my application, I want to include a side-menu which is generated from data in my database. This obviously needs to be done dynamically from a servlet.
Currently, I am sending a blank menu container, then making an ajax call to get the information i need to populate the menu. I would rather just send the menu information along in the original request, so I do not need to waste time making a second request. I used this initial approach because it seemed simpler: I just wrote a gwt rpc service that grabbed the data i needed.
My question is, can I instruct a javascript library like gwt to look for its information in the current web page? Do I have to hide this information in my original HTML response, maybe in a hidden div or something?
If the data that you'd like to embed is restricted to menu items, why not directly generate lightweight HTML out of simple <ol> and <li> elements? You can still keep HTML out of your Java code by using a template engine. The menu markup could just be styled with CSS or if you need something fancier than mere <ol> and <li> elements, you can massage the DOM with JavaScript once the page loads (read: progressive enhancement).
If you're looking for a more generic solution, beyond the menu case, then you could embed a JSON block in your page, to be consumed when the page loads for the dynamic generation of your menu.
Or, you could look into using a microformat that is suitable for menu data.
You can include a script block in the original response defining the data and then use an onload event (or similar) to create the menu based on that data; that's very similar to what you're doing now, but without the extra trip to the server. I'm assuming there that the data to construct the menu is transformed in some way by JavaScript on the client; otherwise, just include the menu markup directly.
GWT has something called JSNI (Javascript Native Interface) that can interface with other non-GWT Javascript. So, you could in your HTML page container have a containing the generated menu items as a Javascript object. Then, in your GWT code, you have a JSNI call to fetch this data and put it in the right place in your UI/DOM with GWT methods.
I asked a similar question a few weeks ago about how to store data safely inside HTML tags. It also contains a few links to other questions. Here
There are in general 2 options:
Store the data in some xml tags somewhere in the html code and later get the information from there by traversing through the DOM. (you can hide them with css)
Store the data as JSON data in a script tag. (There en- and decoders for nearly every language)
var data = { "foo" : "bar", "my_array":[] };

Categories

Resources