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