logo
down
shadow

Constantly read local file with JS?


Constantly read local file with JS?

Content Index :

Constantly read local file with JS?
Tag : javascript , By : user160048
Date : November 28 2020, 04:01 AM

To fix this issue You can enable XmlHttpRequest for local files by starting Chrome with it's security features disabled. This is not an ideal solution but it is the only way to automatically do what you want without running some kind of server. Using Node to watch the file for changes and pushing the data over a WebSocket to the browser would be the proper way to handle this.
Alternatively you could use the FileReader API to open this local file but you need to select it manually through an element first.
function readInputFile(event) {
  let file = event.target.files[0];

  if (!file) {
    return;
  }
  
  let reader = new FileReader();
  
  reader.addEventListener('load', event => {
    let content = event.target.result;
    alert(content);
  });
  
  reader.readAsText(file);
}

document.getElementById('datafile').addEventListener('change', readInputFile, false);
<input type="file" id="datafile">

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

PHP: How to read a file live that is constantly being written to


Tag : php , By : Webtoad
Date : March 29 2020, 07:55 AM
With these it helps I want to read a log file that is constantly being written to. It resides on the same server as the application. The catch is the file gets written to every few seconds, and I basically want to tail the file on the application in real-time. , You need to loop with sleep:
$file='/home/user/youfile.txt';
$lastpos = 0;
while (true) {
    usleep(300000); //0.3 s
    clearstatcache(false, $file);
    $len = filesize($file);
    if ($len < $lastpos) {
        //file deleted or reset
        $lastpos = $len;
    }
    elseif ($len > $lastpos) {
        $f = fopen($file, "rb");
        if ($f === false)
            die();
        fseek($f, $lastpos);
        while (!feof($f)) {
            $buffer = fread($f, 4096);
            echo $buffer;
            flush();
        }
        $lastpos = ftell($f);
        fclose($f);
    }
}

Constantly read a file for a particular string?


Tag : chash , By : Ambarish Singh
Date : March 29 2020, 07:55 AM
it fixes the issue In the assembly, I used a timer to periodically check the .txt file status, something like this:
System.Timers.Timer _logFileCheckTimer;
    public FijiLauncherControl()

    {        // timer set up
                    _logFileCheckTimer = new System.Timers.Timer(250);  
                    _logFileCheckTimer.Enabled = true;
                    _logFileCheckTimer.Elapsed += new System.Timers.ElapsedEventHandler(_logFileCheckTimer_Elapsed);
                   _logFileCheckTimer.Start();  // start the timer

     }    

     void _logFileCheckTimer_Elapsed(object sender, EventArgs e)
        {
            if (_processOn && IsLogOn)
            {
                try
                {
                    _processFinished = CheckStatuts();  // checking file status

                    if (_processFinished) // fire event if checking status returns true
                    {
                        OnIjmFinished(EventArgs.Empty);
                        _processOn = false;
                        _logFileCheckTimer.Stop();
                    }
                }
                catch (Exception ex)
                {

                }
            }
        }
   protected virtual void OnIjmFinished(EventArgs e)
   {
      if (IjmFinished != null)   // trigger event
                IjmFinished(this, e);          
   }
private FijiLauncherControl _fl; // the object of your assembly

  _fl.IjmFinished += new IjmFinishedEventHandler(_fl_IjmFinished); // event from the assembly should trigger an event handler

   void _fl_IjmFinished(object sender, EventArgs e)   // event handler
        {
            _vm.IjmFinished = true;   // a boolean var in viewmodel in main app set to be true once the event from the assembly is triggered

            //throw new NotImplementedException();
        }

PHP: How to constantly read a file


Tag : php , By : micate
Date : March 29 2020, 07:55 AM
I hope this helps you . If your file have only one string, and you need to read it on change, use this code:
$file = '/path/to/test.txt';
$last_modify_time = 0;
while (true) {
    sleep(1); // 1 s
    clearstatcache(true, $file);
    $curr_modify_time = filemtime($file);
    if ($last_modify_time < $curr_modify_time) {
        echo file_get_contents($file);
    }

    $last_modify_time = $curr_modify_time;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"
            type="text/javascript">
    </script>
</head>
<body>
    <div id="file_content"></div>
    <script>
        var time = 0;
        setInterval(function() {
            $.ajax({
                type: "POST",
                data: {time : time},
                url: "fileupdate.php",
                success: function (data) {
                    var result = $.parseJSON(data)
                    if (result.content) {
                        $('#file_content').append('<br>' + result.content);
                    }
                    time = result.time;
                }
            });
        }, 1000);
    </script>
</body>
<?php
$file = 'test.txt';
$result = array();
clearstatcache(true, $file);

$data['time']    = filemtime($file);
$data['content'] = $_POST['time'] < $data['time']
    ? file_get_contents($file)
    : false;

echo json_encode($data);

How do you read a local file on your PC and update it constantly in javascript?


Tag : javascript , By : Terrence Poon
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Doing some more research, it's security reasons as to why you can't access a file from the local computer.
So, in lieu of all that, I made some code that will constantly load the selected file so you can see whenever it changes:
<html>
<head>
<title>Import Data</title>
<script>
var input;

    var openFile = function() {

        var reader = new FileReader(event);
        reader.onload = function() {
            var text = reader.result;
            var node = document.getElementById('output');
            node.innerText = text;
            console.log(reader.result.substring(0,200));
        };

        reader.readAsText(input.files[0]);
        setTimeout(openFile,1000);
    };
</script>
</head>
<body>
<input type='file' accept='text/plain' onchange='input = event.target; openFile(event);'><br>
<div id='output'>
</body>
</html>

How do I read a file which is constantly updating?


Tag : perl , By : Praetoriansentry
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Child component does not set the initial value passed from the parent: ReactJS
  • Nodejs javascript added to button not responding
  • Trying to define a promise.all
  • Python GEE to extract featurecollection timeseries from Landsat imageries
  • How to write negative binary number?
  • Unable to set property of individual object
  • Why Named Function Expression itself cannot assign Name to another Value?
  • How to reset scroll position on single page pagination
  • How to scroll to bottom of page, when a new message is sent - Socket.io
  • How to reconstruct audio blob from a base64 encoded String?
  • How to calculate numbers within an array of objects
  • Using JavaScript to change CSS properties of SVG circles for all circles that was not clicked
  • Is there value in propTypeing repeat required properties at every level of nested components?
  • Call function if variable does not exist in a filter
  • localStorage value doesn't get updated automatically
  • React not updating state with setState correctly inside promises
  • Direct native JavaScript or jQuery method to get containing block of an element
  • Dynamic JSON object to Html Table
  • How to send Id and file to same controller?
  • How to Make a jQuery Table Cell(td) clickable to Run a Function?
  • Prevent the duplicate function onchange event jQuery
  • Reactjs Input Upload doesn't return local URL
  • An unexpected 'StartObject' node was found when reading from the JSON reader. A 'PrimitiveValue' node was expected
  • How to filter a JSON Array, with an eventListener input value at keyup
  • How to separate the different properties of filter in css?
  • Why dont work change event of bootstrap input spinner?
  • How to hide overflow text content in react
  • Is there another way to write line 6
  • Cypress - how to find by text content?
  • How to setstate for the dynamic checkboxes in a loop in react?
  • Is display:none safe?
  • How to create a form to change part of a href url of a button?
  • Put many function inside function in Javascript
  • how to exit from loop after a ajax call
  • Do Angular Reactive Form Validator.min/max check Perform Type Conversions before checking the value?
  • How to Replace Text Within Script Tags Using JQuery
  • add variable to object if not undefined using short-hand
  • How can I effectively curve my items inside a list?
  • Add new record Keyboard Shortcut on Kendo Grid Mvc
  • Time and Date running on page
  • Looping through page links puppeteer doesn't return values from the newly loaded page
  • Problem with Navigator.geoLocation.getCurrentPosition not working
  • Trying to change the id of an element with Javascript
  • Embedded Schema Inserting Blank in Meteor using Collection2
  • avoid useEffect to render at first load?
  • Why is this CSS transition only working correctly on the some clicks? How to solve it?
  • Interpolated values does not reflect the latest values in an Angular app
  • Javascript classes define attribute in constructor or outside the class
  • How to block scroll event passing through to iframe until iframe is active?
  • What is the purpose of "constructor" method in javascript?
  • Stencil JS not working with non-default imports
  • Are frameworks misleadingly named for marketing purposes?
  • React <Redirect> after transition not working
  • How to send multiple parameters in a function using EJS
  • React conditional style on custom click
  • Push a block of information to an array X times based on an external variable
  • How do I populate dropdown with names, and values (numeric ids)?
  • How to apply styling to elements created with .insertAdjacentHtml method
  • Positioning key:value of an object
  • Referencing DOM Elements with React Hooks
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com