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!!

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't want to read file as a <input type="file">,I want to hard code the path of the file directory & read
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 stackoverflow.com/questions/13020821/…
Using a framework like that doesn't really make sense for this task.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.