read a local file in javascript and output certain lines from it - javascript

I am tasked with a little coding challenge that I can't seem to work out. Its meant to be done in javascript, a language I have touched in years... Basically the task is to read a local file , which has sentences on each line. Some of the sentences are palindromes- and the goal is to output only the sentences that are palindromes. I have tried playing around in JSFiddle with the following code. But, my functionality isn't working.
HTML:
<input type="file" name="file" id="file">
Javascript:
window.addEventListener('load', function() {
document.getElementById("myBtn").addEventListener("click", function() {
var reader = new FileReader();
reader.addEventListener('load', function() {
document.getElementById('file').innerText = this.result;
});
reader.readAsText(document.querySelector('input').files[0]);
});
}, true);
console.log(reader);
I found some code online for checking palindromes, but its for a user inputted sentence. I'm struggling to comprehend how to utilize this logic to apply to the lines from my inputted file.
function palindrome(str) {
var re = /[\W_]/g;
var lowRegStr = str.toLowerCase().replace(re, '');
var reverseStr = lowRegStr.split('').reverse().join('');
return reverseStr === lowRegStr;
}
palindrome("A man, a plan, a canal. Panama");
Any ideas or advice? Thanks!

This is a quick solution for the boilerplate code that you got:
Sample file contents:
A man, a plan, a canal. Panama
something else
another line
window.addEventListener('load', function() {
document.getElementById("myBtn").addEventListener("click", function() {
var reader = new FileReader();
reader.addEventListener('load', function() {
//document.getElementById('file').innerText = this.result;
const strings = this.result.split(/\r?\n/);
const palindromes = strings.filter((line) => {
return palindrome(line);
});
console.log('initial lines:', strings);
console.log('palindromes only:', palindromes);
});
reader.readAsText(document.querySelector('input').files[0]);
});
}, true);
//console.log(reader);
function palindrome(str) {
if (str === '') return false;
var re = /[\W_]/g;
var lowRegStr = str.toLowerCase().replace(re, '');
var reverseStr = lowRegStr.split('').reverse().join('');
return reverseStr === lowRegStr;
}
<input type="file" name="file" id="file">
<button id="myBtn">Start</button>

Related

Javascript Filereader only allow .log files?

I have an ASP.NET MVC Application where I can choose a .log File. This happens with a FileReader. But when the explorer opens, all kind of datas are displayed (.png, .jpg, .docx....). So I want, that only the .log Files are displayed.
Here is my code:
// Input File (BUTTON)
const input = document.querySelector('input[type="file"]');
//Get data input from user
input.addEventListener('change', function (e) {
$('#fileName').html(input.files[0].name);
const reader = new FileReader()
reader.onload = function () {
const reslt = reader.result;
readFile(reslt);
}
reader.readAsText(input.files[0])
document.getElementById('rankings').style.display = 'none';
}, false)
This question relates more to html than to javascript. You should use the accept attribute and list a comma separated extensions accepted.
In your case:
<input type="file" accept=".log" />
Try this code.
//Get data input from user
input.addEventListener('change', function (e) {
let kind = $('#fileName').html(input.files[0].name);
if(kind != undefined && kind.indexOf('.log') > 0) {
const reader = new FileReader()
reader.onload = function () {
const reslt = reader.result;
readFile(reslt);
}
reader.readAsText(input.files[0])
document.getElementById('rankings').style.display = 'none';
}
}, false)
Hop is save you day.

Javascript IDs into variables onchange

My html form works perfectly and the javascript works perfectly...the only issue is I obviously don't want to repeat the code 15 times so I need the id's to be pulled into variables.
Simply trying to get three id's from whichever form is submitted onchange. my_btn_id, my_img_id, my_input_id. That's it. I've tried thousands of possible syntax variations, looked up hundreds of answers in here and nothing has not worked the way I need it to. I'm obviously missing something. All help is appreciated.
Here is the simplified html form:
<form action="#” method=" post " id=”my_form_id”>
<input type="file " id="my_input_id "><br>
<button type="submit " value="Upload " id="my_btn_id ">Upload</button>
</form>
Here is javascript - the id's i'm looking for are highlighted with **
$(document).on('change', '.btn-file :file', function () {
var input = $(this),
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [label]);
});
$('.btn-file :file').on('fileselect', function (event, label) {
var input = $(this).parents('.input-group').find(':text'),
log = label;
if (input.length) {
input.val(log);
} else {
if (log) alert(log);
}
});
function readURL(input) {
**var imgid = "#my_img_id";**
**var btnid = "#my_btn_id";**
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(imgid).attr('src', e.target.result);
$(btnid).show();
}
reader.readAsDataURL(input.files[0]);
}
}
**var inputid = "#my_input_id";**
$(inputid).change(function () {
readURL(this);
});
$(this.form) will return the form that contains the input element that the event was triggered on. You can then use this to find the other elements you want.
var form = $(input.form);
var img = form.next("img");
var btn = form.find("input:submit");
There's no need to get their IDs, you can just use the jQuery objects themselves. E.g.
img.attr("src", e.target.result);
btn.show();
Full code:
function readURL(input) {
var form = $(input.form);
var img = form.next("img");
var btn = form.find("input:submit");
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
img.attr('src', e.target.result);
btn.show();
}
reader.readAsDataURL(input.files[0]);
}
}
$("input[type=file]").change(function() {
readURL(this);
});
Many ways to do this.
$("#my_input_id1, #my_input_id2, #my_input_id3").on("change",function(){
var inputItem = $(this);
readURL(inputItem);
});
You can also create variables. For example:
<input type="file" class="inputItem" data-img="my_img_id1" data-btn="my_btn_id1">
<input type="file" class="inputItem" data-img="my_img_id2" data-btn="my_btn_id2">
<input type="file" class="inputItem" data-img="my_img_id3" data-btn="my_btn_id2">
Then with jQuery
$(".inputItem").on("change",function(){
var imgid = $(this).attr("data-img");
var btnid = $(this).attr("data-btn");
// then you can create dynamic selectors
// ...
$("#"+imgid).attr('src', e.target.result);
$("#"+btnid).show();
});
I hope this helps or point you to the right direction!

Find Date in Text and save this Date in variable

I have a txt file which get read with javascript.
function handleTextFile(evt)
{
var files = evt.target.files;
var reader = new FileReader();
reader.onload = function(){
Text = reader.result.toLowerCase();
};
reader.readAsText(files[0]);
}
I want find in var >Text< all Dates.
The located date shall be saved in a variable. The only thing i know-> i can match date formats with code
var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;
but i want not only a true or false output. I want the Value of this located date.
Anyone has a link or a some code for me?
Here is a working snipped with regex for dates in format 00-00-0000.
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
var myRegexp = /\b(\d{2}-\d{2}-\d{4})/g;
var match = myRegexp.exec(reader.result);
fileDisplayArea.innerText = match;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
<div id="page-wrapper">
<h1>Your date reader.</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
I used this tutorial to assemble snipped above .

How to import data from CSV file into Meteor collection at server side

I'm trying to find a solution for my previous post: Mongo gives duplicate key error on _id_ field in Meteor application
In order to do that I want to read data from my CSV file at server side, and not from the client.
First I tried the solution in this post Using node-csv and meteor-file to import CSV into a collection but meteor-file isn't compatible anymore with current version of Meteor. I also tried the solution in this post Upload Data to Meteor / Mongo DB but It's also on the client and that solution generates the same error as in my previous post.
After some further research I tried to read the data with the code below. However it doesn't work:
First I created a collection:
Meteor.orders = new Meteor.Collection('Orders');
I defined the following template to read the csv file:
<template name="read_file_orders">
<form class="well form-inline">
<label class="control-label" for="fileInput2">Kies bestand</label>
<input class="input-file" id="fileInput2" type="file" name="files[]">
<Button class="btn btn-primary" id="read_orders">Importeer</button>
<button class="btn btn-danger" id="erase_orders">Wis gegevens</button>
</form>
</template>
This is the client javascript:
Template.read_file_orders.events({
"click #read_orders" : function(e) {
var f = document.getElementById('fileInput2').files[0];
console.log("read file");
readFile(f, function(content) {
Meteor.call('upload',content);
});
}
});
readFile = function(f,onLoadCallback) {
var reader = new FileReader();
reader.onload = function (e){
var contents=e.target.result
onLoadCallback(contents);
}
reader.readAsText(f);
};
And this is the server javascript:
Meteor.startup(function () {
// code to run on server at startup
return Meteor.methods({
upload : function(fileContent) {
console.log("start insert");
import_file_orders(fileContent);
console.log("completed");
}
});
});
import_file_orders = function(file) {
var lines = file.split('%\r\n');
var l = lines.length - 1;
for (var i=0; i < l; i++) {
var line = lines[i];
var line_parts = line.split('|');
var ex_key = line_parts[0];
var ex_name = line_parts[1];
var clin_info = line_parts[2];
var order_info = line_parts[3];
var clinician_last_name = line_parts[4];
var clinician_first_name = line_parts[5];
var clinician_code = line_parts[6];
var clinician_riziv = line_parts[7]
var pat_id = line_parts[8];
Meteor.orders.insert({Patient:pat_id, Exam_code:ex_key, Exam_name:ex_name, Clinical_info:clin_info, Order_info:order_info, Clinician_first:clinician_first_name, Clinician_last:clinician_last_name, Clinician_c_code:clinician_code, Clinician_riziv:clinician_riziv, Planned:null});
console.log("%");
};
When I try reading the file, nothing happens. Only the console logs appear in the server console but there is nothing imported. Even the Orders collection isn't created.
It's clear that I'm doing something wrong but I don't know what exactly. However I think the solution isn't too far. Maybe someone of you can show me the right direction?
Kind regards
EDIT:
In order to revmen's answer here's the full code of my testapp:
test.html:
<head>
<title>test</title>
</head>
<body>
<h1>Welcome to Meteor!</h1>
{{> read_file_orders}}
</body>
<template name="read_file_orders">
<form class="well form-inline">
<label class="control-label" for="fileInput2">Kies bestand</label>
<input class="input-file" id="fileInput2" type="file" name="files[]">
<Button class="btn btn-primary" id="read_orders">Importeer</button>
<button class="btn btn-danger" id="erase_orders">Wis gegevens</button>
</form>
</template>
test.js
Orders = new Mongo.Collection("orders");
if (Meteor.isClient) {
// counter starts at 0
Template.read_file_orders.events({
"click #read_orders" : function(e) {
var f = document.getElementById('fileInput2').files[0];
console.log("read file");
readFile(f, function(content) {
Meteor.call('upload',content);
});
}
});
import_file_orders = function(file) {
console.log("enter function import_file_orders")
var lines = file.split(/\r\n|\n/);
var l = lines.length - 1;
for (var i=0; i < l; i++) {
var line = lines[i];
var line_parts = line.split(',');
var ex_key = line_parts[0];
var ex_name = line_parts[1];
var clin_info = line_parts[2];
var order_info = line_parts[3];
var clinician_last_name = line_parts[4];
var clinician_first_name = line_parts[5];
var clinician_code = line_parts[6];
var clinician_riziv = line_parts[7]
var pat_id = line_parts[8];
var result = Orders.insert({Patient:pat_id, Exam_code:ex_key, Exam_name:ex_name, Clinical_info:clin_info, Order_info:order_info, Clinician:{first:clinician_first_name, last:clinician_last_name, c_code:clinician_code, riziv:clinician_riziv}, Planned:null});
console.log(Orders.findOne(result));
};
}
readFile = function(f,onLoadCallback) {
//When the file is loaded the callback is called with the contents as a string
var reader = new FileReader();
reader.onload = function (e){
var contents=e.target.result
onLoadCallback(contents);
}
reader.readAsText(f);
};
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
Meteor.methods({
upload : function(fileContent) {
console.log("start insert");
import_file_orders(fileContent);
console.log("completed");
}
});
}
You were very close. I just had to make a few changes to get it working.
I don't know what your .csv file looks like, so I made one that's like this:
A1, B1, C1, D1, E1, F1, G1, H1, I1
A2, B2, C2, D2, E2, F2, G2, H2, I2
Your file.split operation wasn't splitting the lines, but was putting everything on one big line. I did it this way and it worked:
var lines = file.split(/\r\n|\n/);
That got individual lines to split into members of the array. Then I assumed that, since you're calling your input a CSV, your values are separated by commas, not pipes. So I changed your line.split to this
var line_parts = line.split(',');
Other changes I made may not be what was causing yours to fail, but this is how I think things are normally done...
Instead of declaring your collection like this
Meteor.orders = new Meteor.Collection('Orders');
I did it like this
Orders = new Mongo.Collection("orders");
Note that this is run by both the server and the client.
Instead of your way of declaring methods on the server, I just put this into server code (not in Meteor.start):
Meteor.methods({
upload : function(fileContent) {
console.log("start insert");
import_file_orders(fileContent);
console.log("completed");
}
});
And, of course, I changed the insert line at the bottom of your import_file_orders function
var result = Orders.insert({Patient:pat_id, Exam_code:ex_key, Exam_name:ex_name, Clinical_info:clin_info, Order_info:order_info, Clinician_first:clinician_first_name, Clinician_last:clinician_last_name, Clinician_c_code:clinician_code, Clinician_riziv:clinician_riziv, Planned:null});
console.log(Orders.findOne(result));
EDIT for updated code in the question:
Move the import_file_orders function from the client block to the server block.

File Validation in Javascript

We are working on a Email Encrypted Service. Here I have designed a html page (User Registration) where I have provided an area for uploading a file with extentions .crt, .cer and .der
This is HTML Content:
<section>
<label class="label">PubLic Key File</label>
<div>
<input type="file" id="fileInput">
</div>
<div id="fileDisplayArea"></div>
</section>
<button type="submit" class="button">Submit</button>
Javascript Code is:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerHTML = "";
var img = new Image();
img.src = reader.result;
fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!";
}
});
}
I have copied this Javascript Code (beginner in javascript) . It Only Accepts image file. I want to change this code which only accepts .crt, .cer and .der Extentions.
Thank you :)
Your current regex will actually match any filename that contains the word "image" (any part of the filename that is "image" followed by zero or more characters)
If you want to match filenames that end in ".crt", ".cer" or ".der", you can use this regex:
var imageType = /\.crt|cer|der$/
You can test regular expressions using Rubular

Categories

Resources