Jump to content

Read file from computer


Recommended Posts

Hello,

what is the code to load the content of a file from my PC which contains JS code when I use the "try it" screen here, running on chrome, windows10? 

<script scr="?????/javascript">

Thank you.

Edited by JKowalski
Link to post
Share on other sites

The file:/// protocol would be used for this, but browsers don't allow websites to load Javascript files from your filesystem for security reasons.

Link to post
Share on other sites

At first, you need to use a input[type=file] to get a File.

 

<input type=file id=file/>
<div id=result></div>

And then use FileReader to read file to target format, just like base64, text, buffer.

const file = document.getElementById('file').files[0]
const result = document.getElementById('result')
const reader = new FileReader
reader.addEventListener('load', () => {
    result.innerHTML = reader.result
})
reader.readAsText(file, 'UTF-8')

See: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

Link to post
Share on other sites
15 hours ago, Makwana Prahlad said:

At first, you need to use a input[type=file] to get a File.

 


<input type=file id=file/>
<div id=result></div>

And then use FileReader to read file to target format, just like base64, text, buffer.


const file = document.getElementById('file').files[0]
const result = document.getElementById('result')
const reader = new FileReader
reader.addEventListener('load', () => {
    result.innerHTML = reader.result
})
reader.readAsText(file, 'UTF-8')

See: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

If you read the thread instead of just the title, the question was regarding running Javascript from a local file.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...