Reading files using javascript

File и FileReader

Объект File наследуется от объекта Blob и обладает возможностями по взаимодействию с файловой системой.

Есть два способа его получить.

Во-первых, есть конструктор, похожий на Blob :

new File(fileParts, fileName, [options])
  • fileParts – массив значений Blob / BufferSource /строки.
  • fileName – имя файла, строка.
  • options – необязательный объект со свойством:
    • lastModified – дата последнего изменения в формате таймстамп (целое число).

    Во-вторых, чаще всего мы получаем файл из или через перетаскивание с помощью мыши, или из других интерфейсов браузера. В этом случае файл получает эту информацию из ОС.

    Так как File наследует от Blob , у объектов File есть те же свойства плюс:

    В этом примере мы получаем объект File из :

       

    Через можно выбрать несколько файлов, поэтому input.files – псевдомассив выбранных файлов. Здесь у нас только один файл, поэтому мы просто берём input.files[0] .

    FileReader

    FileReader объект, цель которого читать данные из Blob (и, следовательно, из File тоже).

    Данные передаются при помощи событий, так как чтение с диска может занять время.

    let reader = new FileReader(); // без аргументов
    • readAsArrayBuffer(blob) – считать данные как ArrayBuffer
    • readAsText(blob, [encoding]) – считать данные как строку (кодировка по умолчанию: utf-8 )
    • readAsDataURL(blob) – считать данные как base64-кодированный URL.
    • abort() – отменить операцию.

    Выбор метода для чтения зависит от того, какой формат мы предпочитаем, как мы хотим далее использовать данные.

    • readAsArrayBuffer – для бинарных файлов, для низкоуровневой побайтовой работы с бинарными данными. Для высокоуровневых операций у File есть свои методы, унаследованные от Blob , например, slice , мы можем вызвать их напрямую.
    • readAsText – для текстовых файлов, когда мы хотим получить строку.
    • readAsDataURL – когда мы хотим использовать данные в src для img или другого тега. Есть альтернатива – можно не читать файл, а вызвать URL.createObjectURL(file) , детали в главе Blob.

    В процессе чтения происходят следующие события:

    • loadstart – чтение начато.
    • progress – срабатывает во время чтения данных.
    • load – нет ошибок, чтение окончено.
    • abort – вызван abort() .
    • error – произошла ошибка.
    • loadend – чтение завершено (успешно или нет).

    Когда чтение закончено, мы сможем получить доступ к его результату следующим образом:

    Наиболее часто используемые события – это, конечно же, load и error .

       

    Как упоминалось в главе Blob, FileReader работает для любых объектов Blob, а не только для файлов.

    Поэтому мы можем использовать его для преобразования Blob в другой формат:

    • readAsArrayBuffer(blob) – в ArrayBuffer ,
    • readAsText(blob, [encoding]) – в строку (альтернатива TextDecoder ),
    • readAsDataURL(blob) – в формат base64-кодированного URL.

    Для веб-воркеров доступен синхронный вариант FileReader , именуемый FileReaderSync.

    Его методы считывания read* не генерируют события, а возвращают результат, как это делают обычные функции.

    Но это только внутри веб-воркера, поскольку задержки в синхронных вызовах, которые возможны при чтении из файла, в веб-воркерах менее важны. Они не влияют на страницу.

    Итого

    File объекты наследуют от Blob .

    Помимо методов и свойств Blob , объекты File также имеют свойства name и lastModified плюс внутреннюю возможность чтения из файловой системы. Обычно мы получаем объекты File из пользовательского ввода, например, через или перетаскиванием с помощью мыши, в событии dragend .

    Объекты FileReader могут читать из файла или Blob в одном из трёх форматов:

    • Строка ( readAsText ).
    • ArrayBuffer ( readAsArrayBuffer ).
    • URL в формате base64 ( readAsDataURL ).

    Однако, во многих случаях нам не нужно читать содержимое файла. Как и в случае с Blob, мы можем создать короткий URL с помощью URL.createObjectURL(file) и использовать его в теге или . Таким образом, файл может быть загружен или показан в виде изображения, как часть canvas и т.д.

    А если мы собираемся отправить File по сети, то это также легко, поскольку в сетевые методы, такие как XMLHttpRequest или fetch , встроена возможность отсылки File .

    Источник

    FileReader

    The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user’s computer, using File or Blob objects to specify the file or data to read.

    File objects may be obtained from a FileList object returned as a result of a user selecting files using the element, or from a drag and drop operation’s DataTransfer object.

    FileReader can only access the contents of files that the user has explicitly selected, either using an HTML element or by drag and drop. It cannot be used to read a file by pathname from the user’s file system. To read files on the client’s file system by pathname, use the File System Access API. To read server-side files, use standard Ajax solutions, with CORS permission if reading cross-domain.

    Note: This feature is available in Web Workers

    Constructor

    FileReader() Returns a new FileReader object. See Using files from web applications for details and examples.

    Instance properties

    FileReader.error Read only A DOMException representing the error that occurred while reading the file. FileReader.readyState Read only A number indicating the state of the FileReader . This is one of the following:

    Name Value Description
    EMPTY 0 No data has been loaded yet.
    LOADING 1 Data is currently being loaded.
    DONE 2 The entire read request has been completed.

    FileReader.result Read only The file’s contents. This property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation.

    Instance methods

    FileReader.abort() Aborts the read operation. Upon return, the readyState will be DONE . FileReader.readAsArrayBuffer() Starts reading the contents of the specified Blob , once finished, the result attribute contains an ArrayBuffer representing the file’s data. FileReader.readAsBinaryString() Starts reading the contents of the specified Blob , once finished, the result attribute contains the raw binary data from the file as a string. FileReader.readAsDataURL() Starts reading the contents of the specified Blob , once finished, the result attribute contains a data: URL representing the file’s data. FileReader.readAsText() Starts reading the contents of the specified Blob , once finished, the result attribute contains the contents of the file as a text string. An optional encoding name can be specified.

    Events

    Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. Remove the event listeners with removeEventListener() , once FileReader is no longer used, to avoid memory leaks. abort Fired when a read has been aborted, for example because the program called FileReader.abort() . error Fired when the read failed due to an error. load Fired when a read has completed successfully. loadend Fired when a read has completed, successfully or not. loadstart Fired when a read has started. progress Fired periodically as data is read.

    Specifications

    Browser compatibility

    See also

    Found a content problem with this page?

    Источник

    How to read a local text file using JavaScript?

    As you can see, both work differently; one works for an HTML webpage and the other for local Javascript programs.

    File System Package for reading files on your desktop

    The file system package comes with the default node environment for locally hosted JavaScript programs. However, you still need to include the File system package into your javascript code using the required keyword. After that, the function readFile() included in this package allows you to read data from a file.

    Syntax of readFile() method
    The syntax of the readFile() method is given as:

    The details of this syntax are as:

    • FileSystamVar: This is the variable that has been set equal require filesystem package
    • PathToTheFile: This is the path to the file that you want to read
    • Options: These are the optional options that can filter encoding and other attributes of the file
    • CallbackFunction: A callback function that will be executed upon a successful read of the file

    Example 1: Reading a file with File System Package

    Start off by creating a new text file on your computer and place some text inside it like

    After that, head inside your javascript file and include the file system package using the require keyword:

    Then use the following lines:

    fs. readFile ( «demo.txt» , ( err , data ) => {
    if ( err ) throw err ;

    console. log ( data. toString ( ) ) ;
    } ) ;

    The following steps are being performed in the code mentioned above:

    • Read the file “demo.txt
    • If there is an error, then throw that error message onto the terminal
    • In case of no error, store the data read from the file in the data variable
    • Print the content of the data variable after converting it to string using the toString() method

    Upon execution of the code, you will observe the following output on your terminal:

    The data from the file has been printed onto the terminal.

    FileReader Web API for reading files on an HTML webpage

    File reader API only works with HTML web pages, and one of the restrictions of this API is that it works on the files that have been read by input type= “file”> tag. It has multiple functions that allow the user to read the file in different encodings.

    Example 2: Reading a local text file from an HTML webpage

    Start by setting up an HTML webpage, for that use the following lines:

    You will get the following webpage on your browser:

    After that, head over to the javascript file and write down the following lines of code:

    document. getElementById ( «inputFileToRead» )
    . addEventListener ( «change» , function ( ) {
    var fr = new FileReader ( ) ;
    fr. readAsText ( this . files [ 0 ] ) ;
    fr. onload = function ( ) {
    console. log ( fr. result ) ;
    } ;
    } ) ;

    The following steps are being performed in the code mentioned above:

    • An action listener is being applied on your with the id “inputFileToRead
    • Then a object of file reader (fr) has been created using the FileReader() constructor
    • Then the first file on the is being read as a text using the fr variable
    • Upon successful read of the file that data is being printed onto the console

    To demonstrate this, select the same file that was selected in the first example and you will get the following result on the console of your browser:

    The result shows that the file has been successfully read by the HTML webpage.

    Conclusion

    To read a locally placed text file, we have two options: to load the file in HTML or to read that file in your desktop javascript program. For this, you have File Reader Web API for web pages and a file system package for desktop JavaScript. Essentially, both of these perform the same operation: reading a text file. In this tutorial, you have used the readFile() function from the File system package and readFileAsText() from the File Reader Web API.

    About the author

    Abdul Mannan

    I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor’s degree in computer science.

    Источник

    Читайте также:  Php чему равен год
Оцените статью