Writing and reading file via Javascript

Asked

Viewed 31,096 times

15

It is possible (if, how) to do the following method with Javascript?

  • The person type in a form some arguments,
  • by clicking submit it will run a Javascript code,
  • in this code the function will take the form information and will open a file called for example info.txt,
  • it will write the form arguments in that file.

It will also have a standard JS function that will read this file and define the text of a certain place on the page (this part I know how to do, I just need to know how to read the info.txt via Javascript)

4 answers

17


Javascript is executed inside the "environment" of the browser and it is not possible to pass to the operating system, where effectively the document would exist and it would be possible to read and write in it.

What do you want at this time is not possible.

Read files

The most you can do is read a file present on the computer of the person accessing the page using HTML5:

Reading files in Javascript using the File Apis

With the File API we can interact with files present on a computer in order to read the contents of it.

File API support is limited to recent browsers, so it’s not a 100% effective solution to ensure your project will work in every environment.

Write Files

At present, there is an outline in progress for the File API: Writer which will allow writing to files:

This Specification defines an API for writing to files from web Applications.

That translated:

This specification defines an API for writing files from web applications.


Server Side Scripting

Since your question is ambiguous at this point, in case you are referring to Javascript on the server side, you can make use of Node.js and of API File System that it provides to work files on the server side:

File System Node.js v0.10.26 Manual & Documentation


All links in the reply have their content in English.

  • 1

    There is a funny but very limited project to read and write files on the client side: jQuery.twFile. I won’t include it in the answer because to date it requires applets for Webkit browsers (Opera, Safari, Chrome) and doesn’t work in Internet Explorer. But stay here and keep an eye on this :)

  • Thanks for the help!

  • Excellent response!

5

We can create an object Xmlhttprequest to make an HTTP request to one Server-side language, who will be in charge of reading/writing the file. This example will be in PHP.

With Javascript embedded in the HTML file, we call the Ajax function when loading the document and submitting the form:

<!doctype html>
<html>
<head>
    <title>Exemplo Ajax só com JavaScript</title>
</head>
<body>
    <form name='myForm'>
        Trocar ano: <input type='text' id='ano-doc' />
        <input type='button' onclick='ajaxFunction()' value='Ajax!'/>
    </form>
    <div id='ajaxDiv'>Resultado do Ajax</div>

    <script language="javascript" type="text/javascript">
    /**
     * Inspirado em http://www.tutorialspoint.com/php/php_and_ajax.htm
     *
     * @param iniciar Boolean Usando para inicio da página ou envio do formulario
     */
    function ajaxFunction( iniciar ) {
        var ajaxRequest;
        try {
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e) {
            // Internet Explorer Browsers
            try {
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    // Não tem jeito
                    alert( 'Seu browser quebrou!' );
                    return false;
                }
            }
        }
        // Listener que recebe retorno do Ajax
        ajaxRequest.onreadystatechange = function() {
            if( ajaxRequest.readyState == 4 ) {
                var ajaxDisplay = document.getElementById('ajaxDiv');
                ajaxDisplay.innerHTML = ajaxRequest.responseText;
            }
        }

        if( iniciar ) {
            ajaxRequest.open( "GET", "ajax-exemplo.php" , true );
            ajaxRequest.send( null ); 
        } else {
             // Capturar valores e fazer chamada Ajax
            var ano_doc = document.getElementById('ano-doc').value;
            var queryString = "?ano=" + ano_doc ;
            ajaxRequest.open( "GET", "ajax-exemplo.php" + queryString, true );
            ajaxRequest.send( null ); 
       }
    }

    // Roda script ao carregar a página
    ajaxFunction(true);
    </script>        
</body>
</html>

The request will be made to the file ajax-exemplo.php, that will return a result or other as a submission form or not:

<?php    
function escreverArquivo( $arquivo, $ano ) {
    // Let's make sure the file exists and is writable first.
    if ( is_writable( $arquivo ) ) {
        // Write $somecontent to our opened file.
        $content = file_get_contents( $arquivo );
        $somecontent = str_replace( '{ano}', $ano, $content ); 
        file_put_contents( $arquivo, $somecontent );
        echo 'Arquivo atualizado.';  
    } else {
        echo "O arquivo $arquivo não tem permissão de escritura.";
    }
}

function lerArquivo( $arquivo ) {
    $file = new SPLFileObject( $arquivo ); // http://stackoverflow.com/a/9897022/1287812
    echo '<pre><code>';
    foreach( $file as $line ) {
        echo $line;
    }
    echo '</code></pre>';
}

$arquivo = "ajax-exemplo.txt";
if( empty( $_GET['ano'] ) ) { // Primeiro load da página
    lerArquivo( $arquivo );
} else { // Formulário enviado
    escreverArquivo( $arquivo, intval( $_GET['ano'] ) );
}

Finally, the file ajax-exemplo.txt, where {ano} will be replaced by the value sent by the form:

        GNU  GENERAL PUBLIC LICENSE
           Version 2, Junho {ano}

The example of this answer will change the text file only once, since the str_replace() you won’t find {ano} after the first replace.

3

I know the post is old and considered solved, but I researched on the subject, I needed to give a solution to a similar problem.


It is possible to save file via JS?

Yes, it is possible to write a file to a solution client-side!
You can use solutions such as Filesaver.js for a smaller amount of data, or the Streamsaver.js for larger files.

Follow the links of the links:

Filesaver.js:
https://github.com/eligrey/FileSaver.js/

Stramsaver.js
https://github.com/jimmywarting/StreamSaver.js

1

You can create cookies using document.cookie="nomedocookie=valor"; and cookies will be saved together in a line in a txt file in the browser.

To read a cookie, use a function such as:

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
} 

Ex: At some point you send the setar code document.cookie = "nomeusuario=Alexandre"; and then at some point on your website you can recover the value of the cookie nomeusuario with something like:

<script>
nome = getCookie("nomeusuario");
alert("Bem vindo novamente " +  nome);
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.