Javascript begin file with

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 .

    Источник

    Read and write files byte by byte

    Another way to access a file is fs.open() function. Once a file is accessed, you can read data from it using fs.read() function or write data to it using fs.write() function.

    The fs.write() and fs.read() functions use buffer for reading from or writing to a file.

    Open a file for reading or writing using fs.open method

    Syntax: fs.open(path, flags [,mode], callback)

    • path
      Filename and path e.g. D:\BrainBell\map.xml
    • flags
      • r Opens the file for reading
      • r+ Opens the file for reading and writing
      • w Opens the file for writing
      • wx Opens the file for writing, but fails if the file does exist
      • w+ Opens the file for reading and writing
      • wx+ Opens the file for reading and writing, but fails if the file exists
      • a Opens the file for appending
      • ax Opens the file for appending, fails if the file exists
      • a+ Opens the file for reading and appending
      • ax+ Opens the file for reading and appending, but fails if the file exists
      1. error If an error occurs
      2. fd A file descriptor, used by subsequent file operations.

      The following example shows how to open a file for reading:

      //Open a file for reading const file = './file.txt', fs = require('fs'); fs.open(file,'r', (err,fd) => < if (err)< console.log(err); >else < /*. */ >>

      To open a file for writing, just change the flag parameter r to w , for example:

      //Open a file for writing const file = './file.txt', fs = require('fs'); fs.open(file,'w', (err,fd) => < if (err)< console.log(err); >else < /*. */ >>

      What is a file descriptor

      A file descriptor is a handle used to access a file. It is a non-negative integer uniquely referencing a specific file.

      //Print fd const file = './file.txt', fs = require('fs'); fs.open(file,'w', (err,fd) => < if (err)< console.log(err); >else < console.log(fd);//3 >>

      The above example prints fd value, a number, on the screen.

      fs.read() and fs.write()

      Next, we’ll explore how to read the content from an opened file or write content to the opened file.

      • fd
        The fs.open() method’s callback file descriptor
      • buffer
        The buffer used to either hold data to be written or appended, or read
      • offset
        The offset where the input/output (I/O) operation begins in the buffer
      • length
        The number of bytes to read or write in the buffer
      • position
        Position in the file where to begin reading or writing.
      • callback
        The callback functions have three arguments:
        1. err
          An error, if operation failed
        2. bytes
          Bytes read (or written)
        3. buffer
          The buffer.
      //fs.read syntax with callback fs.read( fd, buffer, offset, length, position, (err, bytes, buffer) => < >) //fs.write syntax fs.write( fd, buffer, offset, length, position, (err, bytes, buffer) => < >)

      Reading file content using fs.read method

      Syntax: fs.read(fd, buffer, offset, length, position, callback)

      Files are composed of ordered bytes, and these bytes are addressable by their position . Once we have a file descriptor fd , we can begin to read length number of bytes and insert those into buffer , insertion beginning at a given buffer offset .

      How it all works? Let’s create an app that read a file and print it to the console. I’ve created a file file.txt which contains 26 English alphabets letters:

      //file.txt abcdefghijklmnopqrstuvwxyz

      The following code will read the content of file.txt and print it to the console:

      //readFile.js const fs = require('fs'), len = 26, buff = Buffer.alloc(len), pos = 0, offset =0, file = './file.txt'; fs.open(file, 'r', (err, fd) => < fs.read(fd, buff, offset, len, pos, (err, bytes, buff) =>< console.log(buff.toString()); >); >);

      The Buffer.alloc(len) creates a new Buffer object and allocates it 26 bytes size which is the size of our file. I’ve received the following output:

      D:\BrainBell>node readFile.js abcdefghijklmnopqrstuvwxyz

      Change the len value from 26 to 20 and execute the code again:

      D:\BrainBell>node readFile.js abcdefghijklmnopqrst

      Change the pos value from 0 to 6:

      D:\BrainBell>node readFile.js ghijklmnopqrstuvwxyz

      Writing content to a file using fs.write method

      Syntax: fs.write(fd, buffer, offset, length, position, callback)

      The following example demonstrates how to open a file for writing, file will created if if not already exist:

      const fs = require('fs'), file = './file.txt'; fs.open(file, 'w+', (err, fd) => < let buf = Buffer.from('write this line'); >);

      We created a new Buffer object containing our text to write to file. We’ll read the file after writing the text and print the output to the console:

      fs.open(file, 'w+', (err, fd) => < let buf = Buffer.from('write this line'), pos = 0,offset = 0, len = buf.length; fs.write(fd, buf, offset, len, pos, (err,bytes,buff) => < let buf2 = Buffer.alloc(len); fs.read(fd,buf2,offset, len, pos, (err,bytes,buff2) =>< console.log(buff2.toString()); >); >); >);

      Note: I’ve skipped the error checking for the code clarity.

      In above code, we open a file for reading and writing, then we created a new Buffer object containing our text using Buffer.from method and write it to the file. Then we read the file’s content and prints the output on the console.

      Источник

      How to read and write a file using Javascript?

      The read and write operations in a file can be done by using some commands. But the module which is required to perform these operations is to be imported. The required module is ‘fs’ which is called as File System module in JavaScript.

      Write operation on a file

      After the File System file is imported then, the writeFile() operation is called. The writeFile() method is used to write into the file in JavaScript. The syntax of this method is as follows −

      writeFile(path,inputData,callBackFunction)

      The writeFile() function accepts three parameters −

      • Path − The first parameter is the path of the file or the name of the file into which the input data is to be written. If there is a file already, then the contents in the file are deleted and the input which is given by the user will get updated or if the file is not present, then the file with that will be created in the given path and the input information is written into it.
      • inputData − The second parameter is the input data which contains the data to be written in the file that is opened.
      • callBackFuntion − The third parameter is the function which is the call back function which takes the error as the parameter and shows the fault if the write operation fails.

      Example 1

      Following is an example of the write operation in files in JavaScript.

      const fs = require('fs') let fInput = "You are reading the content from Tutorials Point" fs.writeFile('tp.txt', fInput, (err) => if (err) throw err; else console.log("The file is updated with the given data") > >)

      If you open input file you can observe the written data in it as shown below −

      Reading from the file

      After the File System module is imported, the reading of the file in JavaScript can be done by using the readFile() function.

      Syntax

      The syntax to read from a file is as follows −

      readFile(path, format, callBackFunc)

      The readFile() function accepts three parameters including one optional parameter.

      • Path − The first parameter is the path of the test file from which the contents are to read. If the current location or directory is the same directory where the file which is to be opened and read is located then, only the file name has to be given.
      • Format − The second parameter is the optional parameter which is the format of the text file. The format can be ASCII, utf-8 etc.
      • CallBackFunc − The third parameter is the call back function which takes the error as the parameter and displays the fault is any raised due to the error.

      Example 2

      Following example tries to read the contents of the file populate in the previous example and print it −

      const fs = require('fs') fs.readFile('tp.txt', (err, inputD) => if (err) throw err; console.log(inputD.toString()); >)

      Output

      Following is the output of the above example −

      You are reading the content from Tutorials Point

      The text which is displayed in the console is the text which is in the given file.

      Example 3

      Following is a combined example of the above of reading and writing files using the fs module on node.js. Let us create a JS file named main.js having the following code −

      var fs = require("fs"); console.log("Going to write into existing file"); // Open a new file with name input.txt and write Simply Easy Learning! to it. fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) console.log("Data written successfully!"); console.log("Let's read newly written data"); // Read the newly written file and print all of its content on the console fs.readFile('input.txt', function (err, data) console.log("Asynchronous read: " + data.toString()); >); >);

      Источник

      Читайте также:  Получить предпоследний элемент массива php
Оцените статью