How to read(in), print(out) value to text file by Javascript? - javascript

I'm working on with my simple server. And i need a little data(number) to be used for my project, but i don't want to use database(cuz i don't like SQL). So is there any way that i could save my data in file text and use data in that file text?
I want to use Js to print number from roll call program.htm to hr.txt and then i want read number from hr.txt to roll call program.htm which make a perfect data storage.I tested this kind of saving data in my c++ IDE and it worked, but i don't know if it can work on a server. So can you guys help me out?

Here is a sample code for saving the data as a text file and loading in the HTML.
You can modify this code and use as per your convenience.
function saveTextAsFile()
{
var textToSave = document.getElementById("inputTextToSave").value;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}

Related

How can I use application/vnd.ms-excel with non-Latin languages?

In my app I'm using the below code to export the tblData info into Excel, and it works correctly as long as the content is in English.
function exportTableToExcel(tableID, filename = ''){
var downloadLink;
var dataType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; // or `application/vnd.ms-excel`
var input = document.getElementById(tableID);
var tableSelect = document.createElement("table");
tableSelect = input.cloneNode(true)
const thead = document.createElement("thead");
thead.innerHTML =`
<tr><th>Name</th><th>Skills</th></tr>
`
tableSelect.prepend(thead)
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xlsx':'excel_data.xlsx';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
The output is:
How can I fix it so the non-Latin words (Arabic in case) appear correctly?
Add <meta charset='utf-8'> to the source HTML code.
It's even not necessary to add "html", "head", etc.
This worked for cyrillic; hope your case suits, too.

How to save file from textarea and configure path in download code? JavaScript

The result after clicking the download file is folder download on my computer, but I want a specific path like "\directory\subdirectory" when I click save file.
If javascript isn't possible how can I do it?
<input id="inputFileNameToSaveAs" style="width: 400px;"></input>
<button onclick="saveTextAsFile()" style="width: 250px;">Save File</button>
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type: 'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL !== null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
} else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
There is no possibility to do that. You can download file, but you can't write it in a specific folder. Browser is running in a sandbox for security and don't have access to whole of your computer.
You don't want some javascript on a random page you enter to mess with your computer files.

Change HTML downloadlink into downloadbutton through JavaScript

I'm trying to create a function where I can generate a blob .json file, which I then want to download.
I've checked around and found one way to do it.
function download_rapport(){
var data = geojson.features.map(function(row) { return row.properties; });
var json = JSON.stringify(data);
var blob = new Blob([json], {type: "application/json"});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = "backup.json";
a.href = url;
a.textContent = "Download backup.json";
document.getElementById('content_test').innerHTML = a.outerHTML;
// 'çontent_test' is a <div>
};
This works pretty well, however, this method uses a link to download. I would prefer to use a button, because it fits better with the rest of my application.
I used multiple methods to try and get a download button, but I always end up with a button that sends me to a new page with the data that I need shown as a string.
Is there a way to change my function so that it generates a downloadbutton instead of a downloadlink?
EDIT:
I've edited my code a bit with help from Midas. However, when I alter the data in my var json and try to download the "new" file, it will always download the "first" var json.
What I would like, is to be able to alter the var json data, and always download the "latest" version of it.
window.onload = function testreer() {
var data = geojson.features.map(function(row) { return row.properties; });
var json = JSON.stringify(data);
var blob = new Blob([json], {type: "application/json"});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
var b = document.createElement('button');
a.download = blob;
a.href = url;
b.innerText = 'Download';
document.getElementById('content_test').appendChild(b);
b.appendChild(a);
b.addEventListener('click', function() {
a.click();
});
}
Try this I have append a button in a link if that what you want.
function download_rapport(){
var data = geojson.features.map(function(row) { return row.properties; });
var json = JSON.stringify(data);
var blob = new Blob([json], {type: "application/json"});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = "backup.json";
a.href = url;
// 'çontent_test' is a <div>
var btn = document.createElement('button');
btn.value="download";
btn.innerHTML = "Download JSON";
a.appendChild(btn);
document.getElementById('content_test').innerHTML = a.outerHTML;
};
You can convert it it a button if you like
replace
document.createElement('a');
with
document.createElement("BUTTON");
I decided to give up on changing the link to a button. Instead, I will use CSS to style the link as a button. After checking around I found out that, although it is possible to change a link to a button, it is way faster to just use CSS to style it.
I edited my code a tiny bit by adding a.id = "downloadLink" to give the generated <a> an ID. This ID is then styled in my CSS file.
var a = document.createElement('a');
a.download = "backup.json";
a.href = url;
a.id = "downloadLink";
a.textContent = "Download backup.json";
Since a button has no href attribute like an a tag, you have to assign the desired action to the onclick event on the fly. An example is as follows:
window.onload = function()
{
var url = 'http://lipsum.com';
var btn = document.createElement('button');
btn.innerText = 'Download';
document.getElementById('content_test').appendChild(btn);
btn.addEventListener('click', function(){
window.location.href = url;
});
}
<div id="content_test"></div>
Edit:
Since the file is not coming from a server, you can create both the a tag and the button tag, triggering the link programmatically when the button is clicked:
window.onload = function() {
var url = 'http://lorempixel.com/400/300/technics/';
var a = document.createElement('a');
var b = document.createElement('button');
a.download = 'technics.jpg';
a.href = url;
b.innerText = 'Download';
document.getElementById('content_test').appendChild(b);
b.appendChild(a);
b.addEventListener('click', function() {
a.click();
});
}
<div id="content_test"></div>
However, In normal circumstances you would set Content-Disposition: attachment on the server side, to tell the browser that the file is to be downloaded.

Not able to create .txt file using Chrome

I am a novice to javascript trying to create a .txt file from an .htm document on my PC.
The following code works well with IE, and creates a file (say "A1.txt") on my desktop. However, I can not able to create the file using Chrome. I am running Windows Vista.
Let me know what modification I need to carry out to run this code using Chrome.
Thanks in advance
<html>
<head>
<script type="text/javascript" language="javascript">
</script></head>
<body>
<form name="F1">PN<input type="text" name="T1"></form>
<p><input type="button" value="Submit" onclick="dp()"></p>
</body></html>
<script>
myObject = new ActiveXObject("WScript.Shell");
function dp()
{T1 = "";
var txtfile = "A"+document.F1.T1.value+".txt";
var fso = new ActiveXObject("Scripting.FileSystemObject");
var myFile = fso.OpenTextFile(txtfile,8, true,0);
myFile.write("Test");
myFile.Close();
fso = null;
}
</script>
Please help.
Use the HTML5 File API
function dp() {
if ('Blob' in window) {
var fileName = "A" + document.F1.T1.value;
var textToWrite = "Test";
var textFileAsBlob = new Blob([textToWrite], {
type: 'text/plain'
});
var downloadLink = document.createElement("a");
downloadLink.download = fileName;
downloadLink.innerHTML = "Download File";
if ('webkitURL' in window) {
// Chrome allows the link to be clicked without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
} else {
// Firefox requires the link to be added to the DOM before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
} else {
alert('Your browser does not support the HTML5 Blob.');
}
}
JSFiddle
See more detailed sample here.

Creating Javascript Blob() with data from HTML Element. Then downloading it as a text file

I'm using an HTML5 site to create a log per-say within a textarea element. I need to pull the data from that area with the click of a button, and download it to my computer via a .txt file. How would I go about doing this if it is possible??
HTML:
<input type="button" onclick="newBlob()" value="Clear and Export">
Javascript:
function newBlob() {
var blobData = document.getElementById("ticketlog").value;
var myBlob = new Blob(blobData, "plain/text");
blobURL = URL.createObjectURL(myBlob);
var href = document.createElement("a");
href.href = blobURL;
href.download = myBlob;
href.id = "download"
document.getElementById("download").click();
}
I figure if I make the Blob, create a URL for it, map the URL to an "a" element then auto-click it then it should work in theory. Obviously I'm missing something though. Any help would be fantastic. 1st question on this site btw:p
The simplest way I've come up with is as follows:
function download(text, filename){
var blob = new Blob([text], {type: "text/plain"});
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
}
download("this is the file", "text.txt");
List of possible blob filestypes: http://www.freeformatter.com/mime-types-list.html
const downloadBlobAsFile = (function closure_shell() {
const a = document.createElement("a");
return function downloadBlobAsFile(blob, filename) {
const object_URL = URL.createObjectURL(blob);
a.href = object_URL;
a.download = filename;
a.click();
URL.revokeObjectURL(object_URL);
};
})();
document.getElementById("theButton").addEventListener("click", _ => {
downloadBlobAsFile(new Blob(
[document.getElementById("ticketlog").value],
{type: "text/plain"}
), "result.txt");
});
The value of a download property of an <a> element is the name of the file to download, and the constructor of Blob is Blob(array, options).
I used this approach that doesn't involve creating an element and revokes the textFile after the browser showed the text file
var text = 'hello blob';
var blob = new Blob([text], { type: 'text/plain' });
let textFile = window.URL.createObjectURL(blob);
let window2 = window.open(textFile, 'log.' + new Date() + '.txt');
window2.onload = e => window.URL.revokeObjectURL(textFile);

Categories