Read Write text file using HTML code in Titanium Appcelerator - javascript

I am creating HTML5 type of application in Titanium Appcelerator. I have written code in order to creates text file using using titanium code which executes properly and create text file at /Users/demoUser/Library/Developer/CoreSimulator/Devices/FE1CF0AC-D5BD-4FAB-9615-C58D80B5A9C6/data/Containers/Data/Application/40686DB0-BFB0-4D01-98BB-9E5758C4976D/Documents/file.txt
Now I am having a html file i.e index.html which I am loading in titanium webview within same application. Now I want to access content of file.txt in a function created in .html file.
Anyone who has worked on anything like this before ? Or any help or suggestion regarding this would be appreciated.

You can read a file either from resources directory or application directory and render it in html page like below.
var readContents;
var readFile = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'data.txt');
if (readFile.exists()) {
readContents = readFile.read();
Ti.API.info('File Exists');
}
var docString = readContents.toString();
Ti.API.info('Contents = ' + docString);
var text_in_html = "<html><body><pre>" + docString + "</pre></body></html>";
// Create our Webview
var myWV = Ti.UI.createWebView({
html:text_in_html,
title:'Title goes here',
left:0,
right:0,
top:0,
bottom:0,
loading: true
});

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>

How to get custom ttf font working with jsPDF.output()

I've added the jsPDF library to my Titanium project to generate PDFs client side, which has been working great. But now I want to localize the app for Arabic countries, which means that I have the add a custom font. This works perfectly if you use doc.save('file.pdf'), but it doesn't seem to work correctly for doc.output(). I have to use output because I'm using jsPDF outside of a browser.
To make the library work in Titanium I've had to strip all of the references to window, because it's not running in a browser or webview.
I've tried writing the file from different sources, but nothing seems to yield any results.
My current implementation:
doc = new jsPDF();
var f = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'fonts/markazi-text.regular.ttf');
var contents = f.read();
var base64font = Ti.Utils.base64encode(contents).toString();
doc.addFileToVFS("MarkaziText-Regular", base64font);
doc.addFont('MarkaziText-Regular', 'markazi-text', 'normal');
doc.setFontSize(20);
doc.setFont('markazi-text', 'normal');
doc.text('The quick brown fox jumps over the lazy dog', 20, 20);
var tempFile = Ti.Filesystem.getFile(Ti.Filesystem.getTempDirectory(), 'report.pdf');
if (tempFile.exists()) {
tempFile.deleteFile();
}
tempFile.write(doc.output());
I've also tried to write the file from a blob:
var reader = new FileReader();
reader.onloadend = function () {
tempFile.write(reader.result);
};
reader.readAsText(getBlob(buildDocument()));
But the pdf is empty if I use this. I've also tried the library in a webview within a titanium application, which does work but I don't really want to go that road. It would require too many changes to the code.
Expected:
Actual:
I've finally resolved it by creating a local HTML file. In this HTML file I've loaded jsPDF and my own JavaScript to generate a PDF file. I've loaded this HTML file in a WebView.
I'm generating all the data needed for the PDF in an Alloy controller. I'm sending this data to my WebView JavaScript by firing an app event and catching it in the WebView.
After the PDF is created I trigger an app event in the WebView that contains the base64 data of the jsPDF doc:
Ti.App.fireEvent('app:pdfdone', {
output: doc.output('dataurlstring').replace("data:application/pdf;filename=generated.pdf;base64,", "")
});
I finally save this as a file in the Alloy controller:
var f = Ti.Filesystem.getFile(Ti.Filesystem.getTempDirectory(), 'doc.pdf');
f.write(Ti.Utils.base64decode(e.output));

Programmatically download and insert README.md with photos into HTML

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?

Cannot write to file in Titanium

I am having trouble writing to a file in Titanium Studio.
specifically .json file. Code is compiled through and no exception was thrown.
Here is my relevant section of code, I parse the file to var first before adding element and stringify it to be written back.
Reading works perfectly, so is adding element, it's the writing process that has issues
var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'data.json');
var jsontext = file.read().toString();
var jsondoc = JSON.parse(jsontext);
jsondoc['feedlist'].push({
"picloc":imagename,
"title":titlef.value,
"desc1":descf1.value,
"desc2":descf2.value,
"desc3":descf3.value
});
jsontext = JSON.stringify(jsondoc);
file.write(jsontext); // write(data,[append])
Note: I have consulted Documentation and done some of my own search, some are suggesting that "Filestream" should be used in place of normal file along with .close(), I have yet got them working but it could be pointers the solution, if anyone knows how to get it working
Thanks in advance.
EDIT: This question is flagged for duplication, initially I deemed that was 2 separate issues, one was about merely writing text to a file. Another is parsing event.media (picture) into a file.
I got it working now, The issue was that I was trying to write to file in read-only directory
Ti.Filesystem.resourcesDirectory: A read-only directory where your application resources are located
Ti.Filesystem.applicationDataDirectory: A read/write directory accessible by your app. Place your application-specific files in this directory.
The contents of this directory persist
until you remove the files or until the user uninstalls the application
Here is my code, directory is modified
var sesfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'data2.json');
var jsontext = sesfile.read().toString();
var jsondoc = JSON.parse(jsontext);
jsondoc['feedlist'].push({
"picloc":imagename,
"title":titlef.value,
"desc1":descf1.value,
"desc2":descf2.value,
"desc3":descf3.value
});
jsontext = JSON.stringify(jsondoc);
sesfile.write(jsontext,false);
If you are unable to locate data directory and simply want to load the file from there.
(In my case it does not exist in project nor will be created with Webpreview compilings)
You can do bootstrap-ish type instruction like this first
var rdfile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'data.json');
var sesfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'data2.json');
var jsontext = rdfile.read().toString();
var jsondoc = JSON.parse(jsontext);
sesfile.write(jsontext);
hope it helps whomever makes amateur mistake like I did.

phonegap code get the full path of a file to post in html

I am making a phonegap app for a offline books app. Here i am saving some files in a folder in the root of the device and display all the files in that folder for user to choose. when user clicks on a file to load it i am taking the full path of the file and giving to another javascript function to load it.
The files are saved in myappfolder in the root of the phone and i am getting the file path currectly.
My code is below:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem) {
fileSystem.root.getDirectory("myappfolder",
{
create: true
}, function(directory) {
var directoryReader = directory.createReader();
directoryReader.readEntries(function(entries) {
if(entries.length > 0 ) {
for (i=0; i<entries.length; i++) {
var name = entries[i].name;
var div1 = document.createElement('div');
div1.className = 'books';
div1.id = entries[i].fullPath;
div1.innerHTML = entries[i].name +'<hr>';
document.getElementById('content'). appendChild(div1);
div1.onclick =function (){
redirect(this.id);
}
}
}
When i use this code to load the file i get
network error in file://myappfolder/file.jpg
Kindly help me in solving this as i am new to phonegap.
I am passing this file to another js function which will display this file in a flip book format, It is working fine for me if i give a static file in the app folder
After lots of research i found the solution:
The fullPath gives the path only from the root directory, But if you give
entries[i].toNativeUrl
It is giving the complete path of the file The result of the above code is
file:///storage/emulated/0/myappfolder/name.pdf.
This result came in my phone(samsung galaxy s4)
it works fine in iphone also.
Hope this helps some one else.

Categories