Is it possible to use perl / ajax to read a file line by line while the file is written by another program?

This is similar to the question asked here How to read from a file line by line using an ajax request while the file is written by another program using java? I have a file that will be populated with command line outputs generated from a remote computer. What I would like to do is every time something is written to a file, I want to use perl (or javascript, but I pretty much doubt it) to capture it and display what is written on an open web page . Ideally, each line should be displayed in html as soon as it is written to the file, similar to how it is created in the terminal.

My difficulty is that I'm not sure how I should do the survey - the detection of something is written to a file - and how I can capture the line in real time.

Considering that another possibility that I thought of is to change my script on the remote computer and upload the terminal output to the div of my site. This will avoid recording, reading and polling in real time, but not even sure if this is possible?

+4
source share
1 answer

Ignoring AJAX for a second, Perl usually uses File :: Tail .

With AJAX, you probably have to override File :: Tail. Below is the basic version:

#!/usr/bin/perl

use strict;
use warnings;

use CGI          qw( );
use Fcntl        qw( SEEK_SET );
use Text::CSV_XS qw( decode_json encode_json );

my $qfn = '...';

{
   my $cgi = CGI->new();
   my $request = decode_json( $cgi->param('POSTDATA') || '{}' );
   my $offset = $request->{offset} || 0;

   open(my $fh, '<:raw', $qfn)
      or die("Can't open \"$qfn\": $!\n");

   seek($fh, $offset, SEEK_SET)
      or die("Can't seek: $!\n");

   my $data = '';
   while (1) {
      my $rv = sysread($fh, $data, 64*1024, length($data));
      die("Can't read from \"$qfn\": $!\n") if !defined($rv);
      last if !$rv;
   }

   $offset .= length($data);

   print($cgi->header('application/json'));
   print(encode_json({
      data   => $data,
      offset => $offset,
   }));
}
+7
source

Source: https://habr.com/ru/post/1648046/


All Articles