Text file reading in javascript

Reading a text file using Javascript

The following code should read the content of a text file which is in the current directory upon load, and display it on the html page. I tried modifying by my self. But it does not give an output. Is there an easier way to get this result using another method? or please help figure out what is wrong with this code?

       

Given below is the code which I modified to get the above code. My intention was. As I open the html file it would read the text file which is in the current directory and display the content.

      

Источник

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 a text file using Node.js?

    You’ll want to use the process.argv array to access the command-line arguments to get the filename and the FileSystem module (fs) to read the file. For example:

    // Make sure we got a filename on the command line. if (process.argv.length < 3) < console.log('Usage: node ' + process.argv[1] + ' FILENAME'); process.exit(1); >// Read the file and print its contents. var fs = require('fs') , filename = process.argv[2]; fs.readFile(filename, 'utf8', function(err, data) < if (err) throw err; console.log('OK: ' + filename); console.log(data) >); 

    To break that down a little for you process.argv will usually have length two, the zeroth item being the «node» interpreter and the first being the script that node is currently running, items after that were passed on the command line. Once you’ve pulled a filename from argv then you can use the filesystem functions to read the file and do whatever you want with its contents. Sample usage would look like this:

    $ node ./cat.js file.txt OK: file.txt This is file.txt! 

    [Edit] As @wtfcoder mentions, using the » fs.readFile() » method might not be the best idea because it will buffer the entire contents of the file before yielding it to the callback function. This buffering could potentially use lots of memory but, more importantly, it does not take advantage of one of the core features of node.js — asynchronous, evented I/O.

    The «node» way to process a large file (or any file, really) would be to use fs.read() and process each available chunk as it is available from the operating system. However, reading the file as such requires you to do your own (possibly) incremental parsing/processing of the file and some amount of buffering might be inevitable.

    Источник

    Read and write text file in JavaScript

    You’ll need to provide more context. In a web browser? (You can’t.) In the Windows shell? (Use the FileSystemObject.) In some other environment?

    6 Answers 6

    You need to run the JS in a host environment that provides an API for accessing the file system.

    JS running a browser, under normal security conditions, cannot access the file system.

    If you are using Firefox, this may help.

    //Your text file location on system var savefile = "c:\\yourtextfile.txt"; try < netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); file.initWithPath( savefile ); if ( file.exists() == false ) < alert( "Creating file. " ); file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 ); >var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"] .createInstance( Components.interfaces.nsIFileOutputStream ); outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 ); var output = "Your text here"; var result = outputStream.write( output, output.length ); outputStream.close(); alert("Done"); > catch (e)

    It worked for me, hope works for you as well 🙂

    You can’t. JavaScript in the browser has no access to the user’s filesystem, by design.

    there is an interesting script, in case you are willing to use greasemonkey:

    // ==UserScript== // @name Store notes for every website // @creator Xavi Esteve // @namespace http://www.xaviesteve.com // @description Shows a little notebook at the right bottom of every page that stores any text you type in automatically. Each domain has his separate notebook which can be shown/hidden with a click. // @version 1.3 // @include * // @exclude http*://*.google.*/mail/* // @exclude http*://*.googlemail.* // @exclude file:///* // ==/UserScript== if (self == top) < // VARIABLES var e = document.domain.split(/\./); gdomain = document.domain; var gotit = GM_getValue(gdomain, '[Type notes for '+gdomain+']'); // FUNCTIONS function saveit() < GM_setValue(gdomain, document.getElementById('gm_textarea').value); return false; >/* Insert HTML */ /* div */ var div = document.createElement('div'); div.innerHTML = 'elsereturn false;" title="Notebook">'+gdomain+' '; div.id = "gm_notebook"; document.body.insertBefore(div, document.body.lastChild); /* textarea */ var textarea = document.createElement('textarea'); textarea.appendChild(document.createTextNode(gotit)); textarea.addEventListener('keyup', saveit, false); textarea.addEventListener('click', saveit, false); textarea.id = "gm_textarea"; var gm_title = document.getElementById('gm_title'); gm_title.parentNode.insertBefore(textarea, gm_title.nextSibling); /* Insert CSS */ var menuCode = new Array(); menuCode.push("#gm_notebook #gm_notebook a "); menuCode.push("#gm_tobehiden "); // Change display to block to show the notebook by default menuCode.push("#gm_textarea "); var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = menuCode.join(''); menuCode.length = 0; try < document.getElementsByTagName('head')[0].appendChild(style); >catch(e) <> > 

    Источник

    Читайте также:  Php удалить пустые символы
Оцените статью