Programmatically download and insert README.md with photos into HTML - javascript

I have a personal website written in AngularJS and NodeJS, and in the tech projects section I would like to embed README.md from a project on GitHub my account (the same way github.com) does it. I don't think iframe<> works for md files. So I have tried converting to HTML and PDF.
The second part of the README.md I want looks like this:
In particular, I would like to import the README.md files into my HTML. I have found two ways to do it:
Download the file, and convert to HTML.
var md_to_html = function(src, dest) {
// Get the markdown
var md = fs.readFileSync(src, "utf8");
var converter = new Remarkable();
var html = converter.render(md);
fs.writeFile(dest, html, function(err) {
if (err) {
return console.log(err);
}
console.log(dest + " was saved!");
});
}
Or Download the file, and convert to PDF.
var md_to_pdf = function(src, dest) {
fs.createReadStream(src)
.pipe(markdownpdf())
.pipe(fs.createWriteStream(dest));
}
Both work, however the photo disappears. That is because the dependencies let's say doc/img/photo.jpg does not get downloaded with the README. I have also written scripts to download the dependencies. But neither insert the photo into the README.pdf or README.html.
Has anyone done something like this? Embedded markdown in HTML with photos, or converted them to PDF or HTML with photos? If I could just import it kind of like a PDF with iframe<> that would be ideal, but if not, I will program it myself. But how?

Related

Using three.js: .glb 3d model shows up locally but not on github server, receive SyntaxError: Json.parse

I tried to use three.js to display a 3d model in my personal webpage. The model can be successfully displayed on my local server, however it failed to show up on my web server and I got an error like this:
(links to my .glb file, the main.js, and the index.html file)
I opened my browser web tools and the HTTP response data of my .glb model looks like this:
Any ideas would be highly appreciated.
BH
currently the main.js file looks like this:
$(document).ready(function(){
$nav = $('.nav');
$toggleCollapse = $('.toggle-collapse');
/** click event on toggle menu */
$toggleCollapse.click(function(){
$nav.toggleClass('collapse');
})
});
so it's hard to say exactly what the problem is now, but I'm guessing it was different before.
Without knowing the details of the server code [since you said it was fine in your local server but not on your main server] it's difficult to know the exact details of the issue, but one alternative for loading models without any server at all [but also works through servers] is by making another program [HTML file] that creates a JavaScript loadable file containing the data URL of the file loaded, which can then be included into the main HTML file with a standard script tag [or programmatically], then with the THREE.JS model loader, simply use the dataURL instead of the model URL.
I've persoanlly used this method many times without any server, not even a local server, and I've been able to load all kinds of models [and other files in general].
An example HTML file / code would look something like this:
BH
<br>
data URL-ifier
<br>
<input id="filePicker" type="file">
<br>
<div id="kinTayner"></div>
<script>
filePicker.onchange = () => {
var fr = new FileReader()
fr.onload = () => {
a = document.createElement("a")
kinTayner.innerHTML=""
a.download = filePicker.files[0].name+".html"//or .js,
//but .html files can actually be included in a
//project the same as JS scripts, which can be
//useful if you want to view it quickly in the
//browser
a.innerHTML = "Downlaod the DATA-Urlifier file?!"+
"<br>On GitHub might have to right click->save link as"
var id=Date.now()
a.href = URL.createObjectURL(new Blob([
`
/*BH
\n
<br>
Duel HTML and JavaScript File,
\n<br> can be opened in browser and
\n<br> included as a script, since JavaScript
\n<br>doesn't recognize HTML tags in comments,
\n<br> and JS comments don't affect HTML
<script>
if(!window.dataURLified) {
window.dataURLified = function(d) {
window._fileData_${id} = d;
//to access from console for later use
var m = document.getElementById("${id}")
if(!m) return;
m.innerHTML = "<h1>Your file data!</h1>"+
"<br><h2>"+d.name+"</h2><br>"+
"<a href='" + d.url +
"' target='_blank'>View your file [or right click to download]</a>"
}
}
</`+`script>
<div id="${id}"></div>
<style>
</style>
*/
//<script>
dataURLified({name:"` +
filePicker.files[0].name + `", url: "`+
fr.result
+`"})
// </`+`script>
`
], {type:"text/html"}))
kinTayner.appendChild(a)
}
fr.readAsDataURL(filePicker.files[0])
}
</script>
Then in your main code you can read it by including a script with that name [even if the extension is .html] and define a global function dataURLified [or whatever] to handle the data, here's an example file code [to be used after the above file is generated, and placed in the same directory as the following code, or hosted online, and in the input box enter the URL of that file and open the console]:
<h2>BH</h2><br>
<h3>HTML Fileized Loader</h3>
<input id="loader"> -- enter the name of the file you want to load as script [that was generated b4]
<script>
var files = []
function loadSc(name) {
return new Promise((r,j) => {
var sc = document.createElement("script")
sc.onload=()=>{
r({msg:"Loaded",fl:files[files.length-1]})
}
sc.onerror=(e)=>{
j({msg:"Nope",details:e})
}
sc.src=name;
document.body.appendChild(sc)
})
}
function dataURLified(d) {
//use it here
files.push(d)
}
///somewhere in code, can just call loadSc, just an example
loader.onchange = () => {
loadSc(loader.value)
.then(r=> {
console.log(myFile=r.fl,r.msg,"Use myFile.url for the path!")
}).catch(e=>{
console.log("PRoblem!",e)
})
}
</script>

Extract a non ZIP file to files on disk?

I got a App File which is structured like a zip file.
Now I would like to extract all of the files in the app file.
I tried to convert the app to a zip file in the code (just copy and paste as zip file), but then it's a "SFX ZIP Archive", which most of the unzipper in node.js can't read.
For example AdmZip (error message):
rejected promise not handled within 1 second: Error: Invalid CEN
header (bad signature)
var AdmZip = require('adm-zip');
var admZip2 = new AdmZip("C:\\temp\\Test\\Microsoft_System.zip");
admZip2.extractAllTo("C:\\temp\\Test\\System", true)
So now i don't know how to deal with it, because I need to extract the files with all subfolder/subfiles to a specific folder on the computer.
How would you do this?
You can download the .app file here:
https://drive.google.com/file/d/1i7v_SsRwJdykhxu_rJzRCAOmam5dAt-9/view?usp=sharing
If you open it, you should see something like this:
Thanks for your help :)
EDIT:
I'm already using JSZip for resaving the zip file as a normal ZIP Archive. But this is a extra step which costs some time.
Maybe someone knows how to extract files to a path with JSZip :)
EDIT 2:
Just for you information: It's a VS Code Extension Project
EDIT 3:
I got something which worked for me.
For my solution I did it with Workers (Because parallel)
var zip = new JSZip();
zip.loadAsync(data).then(async function (contents) {
zip.remove('SymbolReference.json');
zip.remove('[Content_Types].xml');
zip.remove('MediaIdListing.xml');
zip.remove('navigation.xml');
zip.remove('NavxManifest.xml');
zip.remove('Translations');
zip.remove('layout');
zip.remove('ProfileSymbolReferences');
zip.remove('addin');
zip.remove('logo');
//workerdata.files = Object.keys(contents.files)
//so you loop through contents.files and foreach file you get the dirname
//then check if the dir exists (create if not)
//after this you create the file with its content
//you have to rewrite some code to fit your code, because this whole code are
//from 2 files, hope it helps someone :)
Object.keys(workerData.files.slice(workerData.startIndex, workerData.endIndex)).forEach(function (filename, index) {
workerData.zip.file(filename).async('nodebuffer').then(async function (content) {
var destPath = path.join(workerData.baseAppFolderApp, filename);
var dirname = path.dirname(destPath);
// Create Directory if is doesn't exists
await createOnNotExist(dirname);
files[index] = false;
fs.writeFile(destPath, content, async function (err) {
// This is code for my logic
files[index] = true;
if (!files.includes(false)) {
parentPort.postMessage(workerData);
};
});
});
});
jsZip is A library for creating, reading and editing .zip files with JavaScript, with a lovely and simple API.
link (https://www.npmjs.com/package/jszip)
example (extraction)
var JSZip = require('JSZip');
fs.readFile(filePath, function(err, data) {
if (!err) {
var zip = new JSZip();
zip.loadAsync(data).then(function(contents) {
Object.keys(contents.files).forEach(function(filename) {
zip.file(filename).async('nodebuffer').then(function(content) {
var dest = path + filename;
fs.writeFileSync(dest, content);
});
});
});
}
});
The file is a valid zip file appended to some sort of executable.
The easiest way is to extract it calling an unzipper such as unzipada.exe - free, open-source software available here. Pre-built Windows executables available in the Files section.

Node JS, Ideas on Template For PDF Creation

How to create PDF Documents in Node.JS.? Is there any better solution to manage templates for different types of PDF creation.
I am using PDFKit to create PDF Documents and this will be server side using Javascript. I can not use HTML to create PDF. It will blob of paragraphs and sections with replacing tags with in.
Does anyone know Node.js has any npm package that can deal templates with paragraphs sections headers.
Something like
getTemplateByID() returns a template that contains sections , headers, paragraphs and then i use to replace appropriate tags within the template.
In my case, I have to get my HTML template from my database (PostgreSQL) stocked as stream. I request the db to get my template and I create a tmp file.
Inside my template, I have AngularJS tags so I compile this template with datas thanks to the 'ng-node-compile' module:
var ngCompile = require('ng-node-compile');
var ngEnvironment = new ngCompile();
var templateHTML = getTemplateById(id);
templateHTML = ngEnvironment.$compile(templateHTML)(datas);
Now I have my compiled template (where you can set your paragraph etc.) and I convert them into PDF thanks to a PhantomJS module 'phantom-html-to-pdf'
var phantomHTML2PDF = require('phantom-html-to-pdf')(options);
phantomHTML2PDF(convertOptions, function (error, pdf) {
if(error) console.log(error);
// Here you have 'pdf.stream.path' which is your tmp PDF file
callback(pdf);
});
Now you have your compiled and converted template (pdf), you can do whatever you want ! :)
Useful links:
https://github.com/MoLow/ng-node-compile
https://github.com/pofider/phantom-html-to-pdf
I hope this help !

Image links in TVML templates created in Swift

I am using local files to feed the templates for an Apple TV project. When I pass the Base URL of where my files reside, and then push the template, embedded image links work fine.
But when I create a template on the fly (as a string), and try to push that, the Base URL is not being read, and I get image links like this:
<heroImg src="${this.BASEURL}myImage.png"></heroImg>
Here is the javascript function that reads the string I create:
function myJSFunction (incomingString) {
if (incomingString) {
Presenter.showLoadingIndicator("defaultPresenter");
var doc = Presenter.makeDocument(incomingString);
Presenter.defaultPresenter.call(Presenter, doc);
}
}
And the strings I am creating don't contain javascript, i.e. they don't start like this:
var Template = function() { return `<?xml version="1.0" encoding="UTF-8" ?>
etc
I know I could write the full Base URL into the image links, but is there any way of keeping the ${this.BASEURL} in the paths I create?

Zipping and Unzipping files in Adobe Air/Javascript

I'm not particularly using Flex but I am using javascript and html and css in a adobe air application. I would like to be able to unzip and zip files. I've looked at a few libraries but none worked as I needed it to. I read somewhere that I could use Fzip library but I need to do this in javascript most preferably but the files are actionscript files. Any advice? Thanks.
You can use almost any actionscript library with html/javascript air app. Example:
Download swc file for airxzip: http://code.google.com/p/airxzip/downloads/list
Rename swc to zip and unzip it
Rename included library.swf to coltware_airxzip.swf
Include the library on your page like this:
<script src="coltware_airxzip.swf" type="application/x-shockwave-flash"></script>
This reads a zip file and writes contents to output folder on the desktop (given you have included jQuery and the AIRAliases.js file from the SDK):
var input = new air.File();
input.addEventListener(air.Event.SELECT, function(event) {
var outputDirectory = air.File.desktopDirectory.resolvePath('output');
var reader = new window.runtime.com.coltware.airxzip.ZipFileReader();
reader.open(event.currentTarget);
$.each(reader.getEntries(), function(i, entry) {
if (!entry.isDirectory()) {
var stream = new air.FileStream();
stream.open(outputDirectory.resolvePath(entry.getFilename()), air.FileMode.WRITE);
stream.writeBytes(reader.unzip(entry));
stream.close();
}
});
});
input.browseForOpen('Select a zip file...', [new air.FileFilter('Zip files', '*.zip')]);
I wrote a sample app for Adobe Air + FZip using javascript.
Figured I'd share that here in case anyone else arrives here via Google.
Can never have too many working examples right?
Example -> http://www.drybydesign.com/?p=233

Categories