Constantly read local file with JS? - javascript

I've been looking all over the place but I can't find a solution to reading a local text file (in the same folder as my js and html files) repeatedly that works with Chrome.
I need to constantly read the file for updates, which another program updates automatically, I don't know how. It's just a regular text.txt file.
I've read a lot of questions/answers on here about it, but so far I've found nothing. Can anyone help?
edit: I meant without node as well, just vanilla JS.

You can enable XmlHttpRequest for local files by starting Chrome with it's security features disabled. This is not an ideal solution but it is the only way to automatically do what you want without running some kind of server. Using Node to watch the file for changes and pushing the data over a WebSocket to the browser would be the proper way to handle this.
Alternatively you could use the FileReader API to open this local file but you need to select it manually through an <input type="file"> element first.
function readInputFile(event) {
let file = event.target.files[0];
if (!file) {
return;
}
let reader = new FileReader();
reader.addEventListener('load', event => {
let content = event.target.result;
alert(content);
});
reader.readAsText(file);
}
document.getElementById('datafile').addEventListener('change', readInputFile, false);
<input type="file" id="datafile">
Edit:
It's 2022 now and we have another way to accomplish this using the File System Access API. It's currently not available in Firefox but this method could be useful if you're only targeting Chromium based browsers (for example: in an Electron app). Note that this feature is only available in secure contexts such as from localhost or over https.
<!DOCTYPE html>
<title> File System Access API Test </title>
<button id="pick"> Pick File </button>
<button id="stop" disabled> Stop Watching </button>
<script>
const pickButton = document.querySelector('button#pick');
const stopButton = document.querySelector('button#stop');
let selected, i;
let pollRate = 15; // seconds
pickButton.addEventListener('click', accessFile);
stopButton.addEventListener('click', stopWatching);
async function accessFile() {
stopWatching();
let [fileHandle] = await window.showOpenFilePicker();
if (fileHandle) {
let f = await fileHandle.getFile();
if (!f) { console.log('failed accessing file'); return ; }
selected = { handle : fileHandle, file : f };
console.log('selected', f.name);
readFile(f);
startWatching();
} else {
console.log('no file selected');
}
}
async function checkFile() {
if (!selected) { return; }
let f = await selected.handle.getFile();
if (f.lastModified > selected.file.lastModified) {
console.log(selected.file.name, 'was updated');
selected.file = f;
readFile(f);
} else {
console.log(selected.file.name, 'had no changes');
}
}
function readFile(f) {
let reader = new FileReader();
reader.addEventListener('load', event => {
console.log(event.target.result);
}); reader.readAsText(f);
}
function startWatching() {
if (i) { clearInterval(i); }
stopButton.disabled = false;
i = setInterval(async ts => {
if (!selected) { return; }
checkFile();
}, pollRate * 1000);
}
function stopWatching() {
clearInterval(i);
i = null;
selected = null;
stopButton.disabled = true;
}
</script>

I think you might be confused what a 'local' file is in this context.
A local file will be loaded with a url such as file://, or selected from a file input in a form.
A file next to your .html and .css is not a local file, it's a hosted file on your web server what you're using to host the .html. You would be referring to it with a relative path to your domain, such as '/file.css'
Node would have more options, seeing that it can read and access local files synchronously with the build in fs ( file system ) library.
What you'll need to do is treat your file like any other on the internet, and download it the same way. Then, download it again later when you need to check for updates. repeat.

Related

Adding an Event Listener for Uploading a File that 'Fires' every time

I am trying to upload an excel file to my react app. I am using an event listener but it is only "picking up" the data the first time I upload a file. For example, I start my local server and then upload a file, test1.xlsx this works correctly. I then upload a second file, test2.xlsx. This also works. However, now if I try to upload either test1.xslx or test2.xlsx. Nothing will appear in the console. My code is as follows:
const input = document.getElementById('input-data')
if(input){
input.addEventListener('change', () => {
var data = [];
readXlsxFile(input.files[0]).then((rows) => {
data.push(rows)
})
console.log(data)
})
}
I am fairly new to all this so I am not sure if there is an event listener other than 'change' that would be better or if it is something to due with how the browser is storing the data. Let me know!
I've had success with this (only showing skeleton, but using this structure to load images):
<input onInput={onSelectFile} type="file" ... />
and
const onSelectFile = (e) => {
const onLoadFn = (dataURL) => {
// processing goes here, maybe something like
setImage(dataURL);
};
if (e.target.files && e.target.files.length > 0) {
const reader = new FileReader();
reader.addEventListener("load", () => onLoadFn(reader.result));
reader.readAsDataURL(e.target.files[0]);
// setState etc could go here, something like
setDialogOpen(true);
}
};

How to get bytes from input type file with jquery [duplicate]

I tried to open file with
window.open("file:///D:/Hello.txt");
The browser does not allow opening a local file this way, probably for security reasons. I want to use the file's data in the client side. How can I read local file in JavaScript?
Here's an example using FileReader:
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
displayContents(contents);
};
reader.readAsText(file);
}
function displayContents(contents) {
var element = document.getElementById('file-content');
element.textContent = contents;
}
document.getElementById('file-input')
.addEventListener('change', readSingleFile, false);
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<pre id="file-content"></pre>
Specs
http://dev.w3.org/2006/webapi/FileAPI/
Browser compatibility
IE 10+
Firefox 3.6+
Chrome 13+
Safari 6.1+
http://caniuse.com/#feat=fileapi
The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.
I currently use this with development versions of Chrome (6.x). I don't know what other browsers support it.
Because I have no life and I want those 4 reputation points so I can show my love to (upvote answers by) people who are actually good at coding I've shared my adaptation of Paolo Moretti's code. Just use openFile(function to be executed with file contents as first parameter).
function dispFile(contents) {
document.getElementById('contents').innerHTML=contents
}
function clickElem(elem) {
// Thx user1601638 on Stack Overflow (6/6/2018 - https://stackoverflow.com/questions/13405129/javascript-create-and-save-file )
var eventMouse = document.createEvent("MouseEvents")
eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
elem.dispatchEvent(eventMouse)
}
function openFile(func) {
readFile = function(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
fileInput.func(contents)
document.body.removeChild(fileInput)
}
reader.readAsText(file)
}
fileInput = document.createElement("input")
fileInput.type='file'
fileInput.style.display='none'
fileInput.onchange=readFile
fileInput.func=func
document.body.appendChild(fileInput)
clickElem(fileInput)
}
Click the button then choose a file to see its contents displayed below.
<button onclick="openFile(dispFile)">Open a file</button>
<pre id="contents"></pre>
Try
function readFile(file) {
return new Promise((resolve, reject) => {
let fr = new FileReader();
fr.onload = x=> resolve(fr.result);
fr.readAsText(file);
})}
but user need to take action to choose file
function readFile(file) {
return new Promise((resolve, reject) => {
let fr = new FileReader();
fr.onload = x=> resolve(fr.result);
fr.readAsText(file);
})}
async function read(input) {
msg.innerText = await readFile(input.files[0]);
}
<input type="file" onchange="read(this)"/>
<h3>Content:</h3><pre id="msg"></pre>
Others here have given quite elaborate code for this. Perhaps more elaborate code was needed at that time, I don't know. Anyway, I upvoted one of them, but here is a very much simplified version that works the same:
function openFile() {
document.getElementById('inp').click();
}
function readFile(e) {
var file = e.target.files[0];
if (!file) return;
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('contents').innerHTML = e.target.result;
}
reader.readAsText(file)
}
Click the button then choose a file to see its contents displayed below.
<button onclick="openFile()">Open a file</button>
<input id="inp" type='file' style="visibility:hidden;" onchange="readFile(event)" />
<pre id="contents"></pre>
Consider reformatting your file into javascript.
Then you can simply load it using good old...
<script src="thefileIwantToLoad.js" defer></script>
Here is how to do it in typescript if Blob is good enough (no need to convert to ByteArray/String via FileReader for many use-cases)
function readFile({
fileInput,
}: {
fileInput: HTMLInputElement;
}): Promise<ArrayLike<Blob>> {
return new Promise((resolve, reject) => {
fileInput.addEventListener("change", () => {
resolve(fileInput.files);
});
});
}
here is how to do it in vanilla javascript
function readFile({
fileInput,
}) {
return new Promise((resolve, reject) => {
fileInput.addEventListener("change", () => {
resolve(fileInput.files);
});
});
}
It is not related to "security reasons" . And it does not matter if it local or file on network drive.
The solution for Windows OS could be IIS - Internet Information Services
and this is some details :
To open file in browser with Java Script window.open() , the file should be available on WEB server.
By creating Virtual Directory on your IIS that mapped to any physical drive you should be able to open files.
The virtual directory will have some http: address.
So instead of window.open("file:///D:/Hello.txt");
You will write window.open("http://iis-server/MY_VIRTUAL_DRIVE_D/Hello.txt");
The xmlhttp request method is not valid for the files on local disk because the browser security does not allow us to do so.But we can override the browser security by creating a shortcut->right click->properties In target "... browser location path.exe" append --allow-file-access-from-files.This is tested on chrome,however care should be taken that all browser windows should be closed and the code should be run from the browser opened via this shortcut.
You can't. New browsers like Firefox, Safari etc. block the 'file' protocol. It will only work on old browsers.
You'll have to upload the files you want.
Javascript cannot typically access local files in new browsers but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.
If you want to read the file abc.txt, you can write the code as:
var txt = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
txt = xmlhttp.responseText;
}
};
xmlhttp.open("GET","abc.txt",true);
xmlhttp.send();
Now txt contains the contents of the file abc.txt.

Import XML file as a string in Javascript [duplicate]

I tried to open file with
window.open("file:///D:/Hello.txt");
The browser does not allow opening a local file this way, probably for security reasons. I want to use the file's data in the client side. How can I read local file in JavaScript?
Here's an example using FileReader:
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
displayContents(contents);
};
reader.readAsText(file);
}
function displayContents(contents) {
var element = document.getElementById('file-content');
element.textContent = contents;
}
document.getElementById('file-input')
.addEventListener('change', readSingleFile, false);
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<pre id="file-content"></pre>
Specs
http://dev.w3.org/2006/webapi/FileAPI/
Browser compatibility
IE 10+
Firefox 3.6+
Chrome 13+
Safari 6.1+
http://caniuse.com/#feat=fileapi
The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.
I currently use this with development versions of Chrome (6.x). I don't know what other browsers support it.
Because I have no life and I want those 4 reputation points so I can show my love to (upvote answers by) people who are actually good at coding I've shared my adaptation of Paolo Moretti's code. Just use openFile(function to be executed with file contents as first parameter).
function dispFile(contents) {
document.getElementById('contents').innerHTML=contents
}
function clickElem(elem) {
// Thx user1601638 on Stack Overflow (6/6/2018 - https://stackoverflow.com/questions/13405129/javascript-create-and-save-file )
var eventMouse = document.createEvent("MouseEvents")
eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
elem.dispatchEvent(eventMouse)
}
function openFile(func) {
readFile = function(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
fileInput.func(contents)
document.body.removeChild(fileInput)
}
reader.readAsText(file)
}
fileInput = document.createElement("input")
fileInput.type='file'
fileInput.style.display='none'
fileInput.onchange=readFile
fileInput.func=func
document.body.appendChild(fileInput)
clickElem(fileInput)
}
Click the button then choose a file to see its contents displayed below.
<button onclick="openFile(dispFile)">Open a file</button>
<pre id="contents"></pre>
Try
function readFile(file) {
return new Promise((resolve, reject) => {
let fr = new FileReader();
fr.onload = x=> resolve(fr.result);
fr.readAsText(file);
})}
but user need to take action to choose file
function readFile(file) {
return new Promise((resolve, reject) => {
let fr = new FileReader();
fr.onload = x=> resolve(fr.result);
fr.readAsText(file);
})}
async function read(input) {
msg.innerText = await readFile(input.files[0]);
}
<input type="file" onchange="read(this)"/>
<h3>Content:</h3><pre id="msg"></pre>
Others here have given quite elaborate code for this. Perhaps more elaborate code was needed at that time, I don't know. Anyway, I upvoted one of them, but here is a very much simplified version that works the same:
function openFile() {
document.getElementById('inp').click();
}
function readFile(e) {
var file = e.target.files[0];
if (!file) return;
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('contents').innerHTML = e.target.result;
}
reader.readAsText(file)
}
Click the button then choose a file to see its contents displayed below.
<button onclick="openFile()">Open a file</button>
<input id="inp" type='file' style="visibility:hidden;" onchange="readFile(event)" />
<pre id="contents"></pre>
Consider reformatting your file into javascript.
Then you can simply load it using good old...
<script src="thefileIwantToLoad.js" defer></script>
Here is how to do it in typescript if Blob is good enough (no need to convert to ByteArray/String via FileReader for many use-cases)
function readFile({
fileInput,
}: {
fileInput: HTMLInputElement;
}): Promise<ArrayLike<Blob>> {
return new Promise((resolve, reject) => {
fileInput.addEventListener("change", () => {
resolve(fileInput.files);
});
});
}
here is how to do it in vanilla javascript
function readFile({
fileInput,
}) {
return new Promise((resolve, reject) => {
fileInput.addEventListener("change", () => {
resolve(fileInput.files);
});
});
}
It is not related to "security reasons" . And it does not matter if it local or file on network drive.
The solution for Windows OS could be IIS - Internet Information Services
and this is some details :
To open file in browser with Java Script window.open() , the file should be available on WEB server.
By creating Virtual Directory on your IIS that mapped to any physical drive you should be able to open files.
The virtual directory will have some http: address.
So instead of window.open("file:///D:/Hello.txt");
You will write window.open("http://iis-server/MY_VIRTUAL_DRIVE_D/Hello.txt");
The xmlhttp request method is not valid for the files on local disk because the browser security does not allow us to do so.But we can override the browser security by creating a shortcut->right click->properties In target "... browser location path.exe" append --allow-file-access-from-files.This is tested on chrome,however care should be taken that all browser windows should be closed and the code should be run from the browser opened via this shortcut.
You can't. New browsers like Firefox, Safari etc. block the 'file' protocol. It will only work on old browsers.
You'll have to upload the files you want.
Javascript cannot typically access local files in new browsers but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.
If you want to read the file abc.txt, you can write the code as:
var txt = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
txt = xmlhttp.responseText;
}
};
xmlhttp.open("GET","abc.txt",true);
xmlhttp.send();
Now txt contains the contents of the file abc.txt.

Can i do a scheduled task programming with javascript?

I want to do a sheduled task for every day.I have multiple servers and i want to automate the upload of html file to my other servers.In this case i have on the same folder my html and my script.js.Im currently using ajax to upload the html file but i want to do that without interference.Here is my javascript.
$(function(){
$("#drop-box").click(function(){
$("#upl").click();
});
// To prevent Browsers from opening the file when its dragged and dropped on to the page
$(document).on('drop dragover', function (e) {
e.preventDefault();
});
// Add events
$('input[type=file]').on('change', fileUpload);
// File uploader function
function fileUpload(event){
$("#drop-box").html("<p>"+event.target.value+" uploading...</p>");
files = event.target.files;
var data = new FormData();
var error = 0;
for (var i = 0; i < files.length; i++) {
var file = files[i];
console.log(file.type);
if(!file.type.match('html.*')) {
$("#drop-box").html("<p> Html only. Select another file</p>");
error = 1;
}else if(file.size > 1048576){
$("#drop-box").html("<p> Too large Payload. Select another file</p>");
error = 1;
}else{
data.append('html', file, file.name);
}
}
if(!error){
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.send(data);
xhr.onload = function () {
if (xhr.status === 200) {
$("#drop-box").html("<p> File Uploaded. Select more files</p>");
} else {
$("#drop-box").html("<p> Error in upload, try again.</p>");
}
};
}
}
This script work fine with my server side, but i want to be able to perform this html upload every day.Is this possible ? what about SetInterval and SetTimeout ?
You can schedule tasks with JavaScript so that they are executed in specific intervals. But you can not upload files from the local system to the server:
JavaScript can't start file transfers on it's own due to security reasons and always needs manual user interaction to do this.
The reason why your above script works is because fileUpload() is orginally triggered by the user. As soon as you use timeout() or interval(), the browser detects that the operation was not triggered by the user and won't allow you to upload user data.

Reading form local file and save into variable [duplicate]

I tried to open file with
window.open("file:///D:/Hello.txt");
The browser does not allow opening a local file this way, probably for security reasons. I want to use the file's data in the client side. How can I read local file in JavaScript?
Here's an example using FileReader:
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
displayContents(contents);
};
reader.readAsText(file);
}
function displayContents(contents) {
var element = document.getElementById('file-content');
element.textContent = contents;
}
document.getElementById('file-input')
.addEventListener('change', readSingleFile, false);
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<pre id="file-content"></pre>
Specs
http://dev.w3.org/2006/webapi/FileAPI/
Browser compatibility
IE 10+
Firefox 3.6+
Chrome 13+
Safari 6.1+
http://caniuse.com/#feat=fileapi
The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.
I currently use this with development versions of Chrome (6.x). I don't know what other browsers support it.
Because I have no life and I want those 4 reputation points so I can show my love to (upvote answers by) people who are actually good at coding I've shared my adaptation of Paolo Moretti's code. Just use openFile(function to be executed with file contents as first parameter).
function dispFile(contents) {
document.getElementById('contents').innerHTML=contents
}
function clickElem(elem) {
// Thx user1601638 on Stack Overflow (6/6/2018 - https://stackoverflow.com/questions/13405129/javascript-create-and-save-file )
var eventMouse = document.createEvent("MouseEvents")
eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
elem.dispatchEvent(eventMouse)
}
function openFile(func) {
readFile = function(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
fileInput.func(contents)
document.body.removeChild(fileInput)
}
reader.readAsText(file)
}
fileInput = document.createElement("input")
fileInput.type='file'
fileInput.style.display='none'
fileInput.onchange=readFile
fileInput.func=func
document.body.appendChild(fileInput)
clickElem(fileInput)
}
Click the button then choose a file to see its contents displayed below.
<button onclick="openFile(dispFile)">Open a file</button>
<pre id="contents"></pre>
Try
function readFile(file) {
return new Promise((resolve, reject) => {
let fr = new FileReader();
fr.onload = x=> resolve(fr.result);
fr.readAsText(file);
})}
but user need to take action to choose file
function readFile(file) {
return new Promise((resolve, reject) => {
let fr = new FileReader();
fr.onload = x=> resolve(fr.result);
fr.readAsText(file);
})}
async function read(input) {
msg.innerText = await readFile(input.files[0]);
}
<input type="file" onchange="read(this)"/>
<h3>Content:</h3><pre id="msg"></pre>
Others here have given quite elaborate code for this. Perhaps more elaborate code was needed at that time, I don't know. Anyway, I upvoted one of them, but here is a very much simplified version that works the same:
function openFile() {
document.getElementById('inp').click();
}
function readFile(e) {
var file = e.target.files[0];
if (!file) return;
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('contents').innerHTML = e.target.result;
}
reader.readAsText(file)
}
Click the button then choose a file to see its contents displayed below.
<button onclick="openFile()">Open a file</button>
<input id="inp" type='file' style="visibility:hidden;" onchange="readFile(event)" />
<pre id="contents"></pre>
Consider reformatting your file into javascript.
Then you can simply load it using good old...
<script src="thefileIwantToLoad.js" defer></script>
Here is how to do it in typescript if Blob is good enough (no need to convert to ByteArray/String via FileReader for many use-cases)
function readFile({
fileInput,
}: {
fileInput: HTMLInputElement;
}): Promise<ArrayLike<Blob>> {
return new Promise((resolve, reject) => {
fileInput.addEventListener("change", () => {
resolve(fileInput.files);
});
});
}
here is how to do it in vanilla javascript
function readFile({
fileInput,
}) {
return new Promise((resolve, reject) => {
fileInput.addEventListener("change", () => {
resolve(fileInput.files);
});
});
}
It is not related to "security reasons" . And it does not matter if it local or file on network drive.
The solution for Windows OS could be IIS - Internet Information Services
and this is some details :
To open file in browser with Java Script window.open() , the file should be available on WEB server.
By creating Virtual Directory on your IIS that mapped to any physical drive you should be able to open files.
The virtual directory will have some http: address.
So instead of window.open("file:///D:/Hello.txt");
You will write window.open("http://iis-server/MY_VIRTUAL_DRIVE_D/Hello.txt");
The xmlhttp request method is not valid for the files on local disk because the browser security does not allow us to do so.But we can override the browser security by creating a shortcut->right click->properties In target "... browser location path.exe" append --allow-file-access-from-files.This is tested on chrome,however care should be taken that all browser windows should be closed and the code should be run from the browser opened via this shortcut.
You can't. New browsers like Firefox, Safari etc. block the 'file' protocol. It will only work on old browsers.
You'll have to upload the files you want.
Javascript cannot typically access local files in new browsers but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.
If you want to read the file abc.txt, you can write the code as:
var txt = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
txt = xmlhttp.responseText;
}
};
xmlhttp.open("GET","abc.txt",true);
xmlhttp.send();
Now txt contains the contents of the file abc.txt.

Categories

Resources