Writing and reading file via JavaScript

11

Is it possible (if so how) to do the following method with JavaScript?

  • The person types in a form some arguments,
  • When you click send it will execute a JavaScript code,
  • In this code the function will get the form information and will open a file named for example info.txt ,
  • it will write the form's arguments to this file.

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

asked by anonymous 03.03.2014 / 23:18

3 answers

13

JavaScript runs within the browser's "environment", it is not possible to move to the operating system, where the document would actually exist and could be read and written to.

What you want is not currently possible .

Read files

The best you can do is to read a file on the person's computer using HTML5:

Reading files in JavaScript using the File APIs

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

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

Write Files

As of today, there is a draft in progress for the File API: Writer that will allow writing to files:

  

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

What translated:

  

This specification defines an API to write files from web applications.

Server Side Scripting

Since your question is ambiguous at this point, in case you're referring to the server-side JavaScript, you can use node.js and the API File System that it provides for working on server-side files:

File System Node.js v0.10.26 Manual & Documentation

All links in the response have their content in English.

    
03.03.2014 / 23:40
3

We can create an XMLHttpRequest object to make an HTTP request to a Server-side language , which will be responsible for 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 sending 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 , which will return a result or another as a form submission 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 response will change the text file only once, since str_replace() will not find {ano} after the first replace .

    
08.09.2014 / 17:41
0

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 code setar document.cookie = "nomeusuario=Alexandre"; and then at some point on your site you can retrieve the value of the cookie nomeusuario with something like:

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