1

I want to read a text file which is in my local directory,I found many examples they have used httprequest()I don't want to use any of the servers like xampp,wampp etc

I am using JS!!

Ram
  • 55
  • 1
  • 7

1 Answers1

0

Best partice is always us php,nodeJS or backend langaugae to do such things, but in your case you might use angularJS .

Add the below in your JS

    var myapp = angular.module('myapp', []);

myapp.controller('MainCtrl', function ($scope) {
    $scope.showContent = function($fileContent){
        $scope.content = $fileContent;
    };
  });

myapp.directive('onReadFile', function ($parse) {
    return {
        restrict: 'A',
        scope: false,
        link: function(scope, element, attrs) {
            var fn = $parse(attrs.onReadFile);

            element.on('change', function(onChangeEvent) {
                var reader = new FileReader();

                reader.onload = function(onLoadEvent) {
                    scope.$apply(function() {
                        fn(scope, {$fileContent:onLoadEvent.target.result});
                    });
                };

                reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
            });
        }
    };
});

The below is the HTML body:

<div ng-controller="MainCtrl" class="container">
  <h1>Select text file</h1>
    <input type="file" on-read-file="showContent($fileContent)" />
    <div ng-if="content">
        <h2>File content is:</h2>
        <pre>{{ content }}</pre>
    </div>
</div>

Keep in mind that read, write and save function should always be done in back-end side.

Anson Aştepta
  • 1,125
  • 2
  • 14
  • 38
  • I don't want to read file as a ,I want to hard code the path of the file directory & read – Ram Mar 07 '16 at 05:05
  • you can do it on your own, just declare a new variable and place it as default, then it will do as you say. like var Url = "/desktop/text.txt" ; . You can also take a look in http://stackoverflow.com/questions/13020821/how-to-load-json-into-my-angular-js-ng-model – Anson Aştepta Mar 07 '16 at 05:58
  • Using a framework like that doesn't really make sense for this task. – kriskotoo BG Jul 30 '20 at 06:48