- How to read text file in JavaScript
- 7 Answers 7
- Document: open() method
- Syntax
- Parameters
- Return value
- Examples
- Notes
- Content Security
- Three-argument document.open()
- Two-argument document.open()
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Hello World!
- See Also:
- Syntax
- Parameters
- Return Value
- More Examples
- Hello World!
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Window open()
- See Also:
- Syntax
- Parameters
- Deprecated
- Warning
- Return Value
- More Examples
- Browser Support
- Open Local Text File Using JavaScript
- Use JavaScript FileReader() to Open Local Text File
- Use JavaScript FileReader() and jQuery to Open Local Text File
- Use JavaScript Promise and FileReader to Open Local Text File
- Related Article — JavaScript File
How to read text file in JavaScript
I am trying to load a text file into my JavaScript file and then read the lines from that file in order to get information, and I tried the FileReader but it does not seem to be working. Can anyone help?
function analyze() < var f = new FileReader(); f.onloadend = function()< console.log("success"); >f.readAsText("cities.txt"); >
Read: html5rocks.com/en/tutorials/file/dndfiles. If it’s a local file, the user has to select the file itself for security reasons. Related: stackoverflow.com/questions/13428532/…
7 Answers 7
Yeah it is possible with FileReader, I have already done an example of this, here’s the code:
Contents of the Text file:
.
It’s also possible to do the same thing to support some older versions of IE (I think 6-8) using the ActiveX Object, I had some old code which does that too but its been a while so I’ll have to dig it up I’ve found a solution similar to the one I used courtesy of Jacky Cui’s blog and edited this answer (also cleaned up code a bit). Hope it helps.
Lastly, I just read some other answers that beat me to the draw, but as they suggest, you might be looking for code that lets you load a text file from the server (or device) where the JavaScript file is sitting. If that’s the case then you want AJAX code to load the document dynamically which would be something as follows:
Document: open() method
The Document.open() method opens a document for writing.
This does come with some side effects. For example:
- All event listeners currently registered on the document, nodes inside the document, or the document’s window are removed.
- All existing nodes are removed from the document.
Syntax
Parameters
Return value
A Document object instance.
Examples
The following simple code opens the document and replaces its content with a number of different HTML fragments, before closing it again.
.open(); document.write("Hello world!
"); document.write("I am a fish
"); document.write("The number is 42
"); document.close();
Notes
An automatic document.open() call happens when document.write() is called after the page has loaded.
Content Security
This method is subject to the same same-origin policy as other properties, and does not work if doing so would change the document’s origin.
Three-argument document.open()
There is a lesser-known and little-used three-argument version of document.open() , which is an alias of Window.open() (see its page for full details).
This call, for example opens github.com in a new window, with its opener set to null :
.open("https://www.github.com", "", "noopener=true");
Two-argument document.open()
Browsers used to support a two-argument document.open() , with the following signature:
Where type specified the MIME type of the data you are writing (e.g. text/html ) and replace if set (i.e. a string of «replace» ) specified that the history entry for the new document would replace the current history entry of the document being written to.
This form is now obsolete; it won’t throw an error, but instead just forwards to document.open() (i.e. is the equivalent of just running it with no arguments). The history-replacement behavior now always happens.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.
const myWindow = window.open();
myWindow.document.open();
myWindow.document.write(«
Hello World!
«);
myWindow.document.close();
Do not confuse this method with the window.open() method, which opens a new browser window.
See Also:
Syntax
Parameters
Parameter | Description |
Mimetype | Ignored by all modern browsers. |
replace | Ignored by all modern browsers. |
Return Value
More Examples
If document.write() is used on a closed document, document.open() is automatically called. This will delete existing content.
document.write(«
Hello World!
«);
Browser Support
document.Open() is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Window open()
The open() method opens a new browser window, or a new tab, depending on your browser settings and the parameter values.
See Also:
Syntax
Parameters
Deprecated
- true — URL replaces the current document in the history list
- false — URL creates a new entry in the history list
Warning
Chrome throws an exception when using this parameter.
Return Value
More Examples
Open an about:blank page in a new window/tab:
Open a new window called «MsgWindow», and write some text into it:
var myWindow = window.open(«», «MsgWindow», «width=200,height=100»);
myWindow.document.write(«
This is ‘MsgWindow’. I am 200px wide and 100px tall!
«);
Replace the current window with a new window:
var myWindow = window.open(«», «_self»);
myWindow.document.write(«
I replaced the current window.
«);
Open a new window and control its appearance:
window.open(«https://www.w3schools.com», «_blank», «toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400»);
Open a new window. Use close() to close the new window:
function openWin() <
myWindow = window.open(«», «myWindow», «width=200,height=100»); // Opens a new window
>
function closeWin() myWindow.close(); // Closes the new window
>
Open a new window. Use the name property to return the name of the new window:
var myWindow = window.open(«», «MsgWindow», «width=200,height=100»);
myWindow.document.write(«
This window’s name is: » + myWindow.name + «
«);
Using the opener property to return a reference to the window that created the new window:
var myWindow = window.open(«», «myWindow», «width=200,height=100»); // Opens a new window
myWindow.document.write(«
This is ‘myWindow’
«); // Text in the new window
myWindow.opener.document.write(«
This is the source window!
«); // Text in the window that created the new window
Browser Support
open() is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
Open Local Text File Using JavaScript
- Use JavaScript FileReader() to Open Local Text File
- Use JavaScript FileReader() and jQuery to Open Local Text File
- Use JavaScript Promise and FileReader to Open Local Text File
Our objective is to guide you about various techniques and methods that you can use to open a local text file using JavaScript. It also demonstrates the use of FileReader() , Promise , and different jQuery functions and events to read a text file from your system.
Use JavaScript FileReader() to Open Local Text File
html> head> title>Read Text Filetitle> head> body> input id='selectedfile' type='text' name='selectedfile'> input id='inputfile' type='file' name='inputfile' onChange='showSelectedFile()'> br>br> pre id="output">pre> body> html>
input[type=file] width:90px; color:transparent; >
function showSelectedFile() selectedfile.value= document.getElementById("inputfile").value; > document.getElementById('inputfile') .addEventListener('change', function() var fr=new FileReader(); fr.onload=function() document.getElementById('output') .textContent=fr.result; > fr.readAsText(this.files[0]); >)
This code prints the content of the selected file (input file) the same as it is written in the input file.
The showSelectedFile() method shows the input file’s path. Then, the element whose id’s value is inputfile gets selected.
The event listener listens to the input for changes. Here, it is changed when file(s) are chosen.
As soon as it is changed, an anonymous function runs that creates a FileReader object using the FileReader() constructor and names it fr . Using fr , we can access different functions and attributes of FileReader() . This function reads the text content and displays it in the browser.
The .onload is used to launch a particular function. In our case, this function selects the first element having id as output and sets its .textContent property with the value of .result .
.textContent reads the content of current element (node) and its descendant elements. .readAsText() reads the content of the given input file. Once it reads all the content, the result attribute has this content as a string.
The FileList is returned by the input element’s files property. In this example, it is assumed that this is an input element that returns the file object at index zero ( this.files[0] ).
Use JavaScript FileReader() and jQuery to Open Local Text File
html> head> title>Read Text Filetitle> script src="https://code.jquery.com/jquery-3.5.1.min.js">script> head> body> input type="file" name="inputfile" id="inputfile"> br>br> pre id="output">pre> body> html>
$(document).ready(function() $("#inputfile").change(function() var file = this.files[0]; var fr=new FileReader(); fr.onload=function(data) $("#output").html(data.target.result); > fr.readAsText(file); >); >);
Hey, Are you learning about how to open a local text file using JavaScript?
This sample code also prints the content for the input file as it is written in the file (input file).
The ready() event triggers when the document object model (DOM) is fully loaded. To understand easily, you can say that it makes a method accessible after loading the document.
The change() event is used to know if the value of the element is changed. We can use change() event only with input , textarea , and select elements. It can either triggers the change() event or executes a function on change() event.
.html() is very useful if you want to return or set the innerHTML (content) of the chosen elements.
Now, you might think about how the innerHTML is being changed? It is due to targeting the result attribute of FileReader .
Have a look at the following screenshot (outlined in orange color).
The .onload , .result , .readAsText() are already explained in previous section. You can go there to have a look or check this link to read in detail.
You can use File-System to read a local text file (if you are coding on Node Environment).
Use JavaScript Promise and FileReader to Open Local Text File
html> head> title>Read Text Filetitle> head> body> input type="file" onchange="readInputFile(this)"/> h3>File Content:h3> pre id="output">pre> body> html>
function readFile(file) return new Promise((resolve, reject) => let freader = new FileReader(); freader.onload = x=> resolve(freader.result); freader.readAsText(file); >)> async function readInputFile(input) output.innerText = await readFile(input.files[0]); >
Hey, Are you learning about how to open a local text file using JavaScript?
In this example code, the function readInputFile() runs as soon as the input file is selected. This function will wait (using the await operator) for the Promise to be fulfilled and return the expected value (if resolved).
Further, the content ( innerHTML ) of the element having id output will be replaced with the value returned by Promise . The await operator is used to waiting for the Promise , it is an object that represents pass or fails of an asynchronous function and its respective value. It has three states named resolve , reject , and pending .
Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.