From .txt data give values to inputs - javascript

I'm trying to fill some inputs when you load a page, using the data I have from a .txt file. This file has a list of numbers
1
2
3
Something like this. So I wanted to read this lines and put them in their corresponding input. Suggestions on how to do this??
I tried with this code, but maybe I have a mistake that I don't know about, I'm starting with javascript.
function loadvalues()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.OpenTextFile("E://Steelplanner/Demand_Routing/Pruebas/OrderBalancing_Masivos/ModificaFechaTope/DueDate/Datosactuales.txt", true);
var Ia5 = document.getElementById("Ia5sem");
var text = s.ReadLine();
Ia5.value = text;

Try using file.ReadLine() until document not completely read using while loop with AtEndOfStream of file variable.
Here is example you can refer: ReadLine Method
Don't forget to replace TextFile path to your own text file path
My text file contains same data as in your example
<script type="text/javascript">
var fso = new ActiveXObject("Scripting.FileSystemObject");
//specify the local path to Open and always add escape character else throw error for bad file name
var file = fso.OpenTextFile("C:\\Users\\MY_USER\\Desktop\\txtfile.txt", 1);
var Ia5 = document.getElementById("Ia5sem");
while (!file.AtEndOfStream) {
var r = file.ReadLine();
Ia5.innerHTML = Ia5.innerHTML + ("<br />" + r);
}
file.Close();
</script>
<p id="Ia5sem">HI</p>

So, I don't know why, but I just changed the name of the variables and made a slight change in the .OpenTextFile line and it worked.
function loadvalues()
{
var file = new ActiveXObject("Scripting.FileSystemObject");
var text = file.OpenTextFile("E:\\Steelplanner\\Demand_Routing\\Pruebas\\OrderBalancing_Masivos\\ModificaFechaTope\\DueDate\\Datosactuales.txt", 1,false);
var Ia5s = document.getElementById("Ia5sem");
Ia5s.value = text.ReadLine();
var Ia4s = document.getElementById("Ia4sem");
Ia4s.value = text.ReadLine();
text.close();
}
Anyways, I'm gonna check the FileReader() for future references and the script #Sarjan gave, maybe I can improve it, but I have other things to finish. Thanks for everything.

Related

How to read any local file by chunks using JavaScript?

How can I read any large file(greater than 1 gigabytes) locally by chunks(2kb or more),and then convert the chunk to a string, process the string and then get the next chunk and so on until the end of the file?
I'm only able to read small files and convert it to string, as you can see from the code I don't know how to read the file by chunks. The browser freezes if I try it with a file greater than 10mb.
<html>
<head>
<title>Read File</title>
</head>
<body>
<input type="file" id="myFile">
<hr>
<textarea style="width:500px;height: 400px" id="output"></textarea>
<script>
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (e) {
output.textContent = e.target.result;
});
reader.readAsBinaryString(myFile);
}
});
</script>
</body>
</html>
Below are the links and answers I found on StackOverflow whilst researching on how to accomplish it, but it didn't solve my question.
1: This question was asking about how to do it using UniversalXPConnect, and only in Firefox, which is why i found the answer there to be irrelevant, because I use Chrome and don't know what UniversalXPConnect is.
How to read a local file by chunks in JavaScript
2: This question was asking about how to read text files only, but I want to be able to read any file not just text, and also by chunks, which makes the answers there irrelevant, but i liked how short the code of the answer was. Reading local text file into a JavaScript array [duplicate]
3: This also is about text files and doesn't show how to read files by chunks How to read a local text file.
I know a little bit of Java, which you can easily do it by;
char[] myBuffer = new char[512];
int bytesRead = 0;
BufferedReader in = new BufferedReader(new FileReader("foo.mp4"));
while ((bytesRead = in.read(myBuffer,0,512)) != -1){
...
}
but I'm new to javascript
I was able to solve it by slicing the file by specifying attributes of where to begin the slice and where to end which will be the chunk, I then enclosed it in a while loop so that for each loop chunk position will shift according to the desired chunk size until the end of the file.
But after running it, I end up getting the last value of the chunk in the text area, so to display all the binary string i concatenate the output on each iteration.
<html>
<head>
<title>Read File</title>
</head>
<body>
<input type="file" id="myFile">
<hr>
<textarea style="width:500px;height: 400px" id="output"></textarea>
<script>
var input = document.getElementById("myFile");
var output = document.getElementById("output");
var chunk_size = 2048;
var offset = 0;
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var size = myFile.size; //getting the file size so that we can use it for loop statement
var i=0;
while( i<size){
var blob = myFile.slice(offset, offset + chunk_size); //slice the file by specifying the index(chunk size)
var reader = new FileReader();
reader.addEventListener('load', function (e) {
output.textContent += e.target.result; //concatenate the output on each iteration.
});
reader.readAsBinaryString(blob);
offset += chunk_size; // Increment the index position(chunk)
i += chunk_size; // Keeping track of when to exit, by incrementing till we reach file size(end of file).
}
}
});
</script>
</body>
</html>
So the issue isn't with FileReader, it's with :
output.textContent = e.target.result;
Because you are trying to dump 10MB+ worth of string into that textarea all at once. I'm not even sure there is a "right" way to do what you are wanting, since even if you did have it in chunks, it would still have to concat the previous value of output.textContent on each loop through those chunks, so that as it gets closer to the end, it would start slowing down in the same way (worse, really, because it would be doing the slow memory hogging business on every loop). So I think part of the looping process is going to have to be adding a new element (like a new textarea to push the current chunk to (so it doesn't have to do any concatenation to preserve what has already been output). I haven't worked that part out yet, but here's what I've got so far:
var input = document.getElementById("myFile");
var output = document.getElementById("output");
var chunk_length = 2048; //2KB as you mentioned
var chunker = new RegExp('[^]{1,' + chunk_length + '}', 'g');
var chunked_results;
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (e) {
chunked_results = e.target.result.match(chunker);
output.textContent = chunked_results[0];
});
reader.readAsBinaryString(myFile);
}
});
This is just outputting the first string in the array of 2KB chunks. You would want to do your thing as far as adding a new element/node in the DOM document for outputting all the other chunks.
Using RegExp and match for the actual chunking was lifted from a clever gist I found.
You can do that using fs.createReadStream(), The amount of data potentially buffered depends on the highWaterMark option passed into the streams constructor.
So you would do it like this:
var read = fs.createReadStream('/something/something', { highWaterMark: 64 });
here's an example :
var fs = require('fs')
var read = fs.createReadStream('readfile.txt',{highWaterMark:64})
var write = fs.createWriteStream('written.txt')
read.on('open', function () {
read.pipe(write);
});
see how it reads 64 bytes at a time (Very Slow), you can view it on explorer in a fun way, but make sure you have a large text file to test it not a gigabyte but at least 17 megabytes like I did "fill it with any dummy text"
make the file view to "details" and keep refreshing the destination in windows explorer, you will see the size increase on every refresh.
I assumed you know about the pipe method if you don't, no problem! it's very simple, here is a link:
https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
or a quick explanation :
readable.pipe(writable)
The pipe() function reads data from a readable stream as it becomes available and writes it to a destination writable stream.

How do I get rid of everything, every string before a specified word in jquery?

I'm trying to do a simple string replace in jquery but it seems to be more than just a simple code.
In mygallery have this image link (note the 2x ../)
var imgName= '../../appscripts/imgs/pic_library/burn.jpg';
In browsegallery I have something like this:
var imgName ='../../../../../appscripts/imgs/pic_library/burn.jpg';
and sometimes depending on where do I get the image source from, it can be like this
var imgName = '../appscripts/imgs/pic_library/burn.jpg';
What I'm trying to do is, to get rid of all of those '../', and to gain the imgName like this:
'appscripts/imgs/pic_library/burn.jpg';
So this way I can get the right directory for my mobile app.
Can anyone help me on how to get rid of all those (without even counting) '../'?
Best Regards!
Using the replace method of a string you can remove all cases of the
../
var imgPath = '../../../../../appscripts/imgs/pic_library/burn.jpg';
var imgName = imgPath.replace(/\.\.\//g, '');
console.log(imgName);
Here is a direct answer to your question that does not tie you to the "/appscripts" in your example:
const imgName= '../../appscripts/imgs/pic_library/burn.jpg';
const img = imgName.split('../')
.filter((val) => val !== '')
.join('');
If the desired end path is always the same - just get the unique part (the actual file name) and add it to a string of the path you require. the following usies lastIndexOf to get the actual file name from the relative path and then builds a string to give the desired path plus the file name.
var fileSource = 'appscripts/imgs/pic_library/burn.jpg';
let lastIndex = fileSource.lastIndexOf('/');
let fileName = fileSource.slice(lastIndex + 1, fileSource.length); // gives burn.jpg
let imageSource = 'appscripts/imgs/pic_library/' + fileName;
console.log(imageSource); // gives appscripts/imgs/pic_library/burn.jpg
Thank you all for helping me out.
I finally solved this using imgName.split('/appscripts/');
Like this:
var replaceImg = image.split('/appscripts/');
var finalImageName = "../../../appscripts/"+replaceImg[1];
Thank you again!
You can create a jQuery plugin, i.e: $(...).imagify()
Use a regex to replace that pattern: .replace(/(\.){1,2}\//g, '')
$.fn.imagify = function() {
var src = this.attr('src') || '';
this.attr('src', src.replace(/(\.){1,2}\//g, ''));
};
$('img').imagify();
$('img').each((_, obj) => console.log($(obj).attr('src')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src='../../../../../appscripts/imgs/pic_library/burn.jpg'>
<img src='../appscripts/imgs/pic_library/burn.jpg'>
<img src='./../../appscripts/imgs/pic_library/burn.jpg'>
Resource
How to Create a Basic Plugin

how to propely assemble csv file to avoid column shift

in my node app, I'm trying to clean up a csv file.
first, I split it into separate lines
then I replace unwanted characters in the first line (the column headers)
then I re-assemble the file by pushing individual lines into a new array, and writing that array to a new .csv file
For some reason, all my rows ending up being shifted by 1 position with respect to the header row.
I have opened the resulting file in a vu editor, and can see, that all rows somehow acquired a "," character at the besieging
I know I'm doing something incorrectly, but can not see what that is.
Here is my code:
var XLSX = require('xlsx');
var fs = require('fs');
var csv = require("fast-csv");
var workbook = XLSX.readFile('Lineitems.xls');
var worksheet = workbook.Sheets['Sheet1'];
var csv_conversion = XLSX.utils.sheet_to_csv(worksheet);
var csv_lines = csv_conversion.split('\n');
var dirtyHeaderLine = csv_lines[0];
var cleanHeaderLine = dirtyHeaderLine.replace(/\./g,"")
.replace(/"'"/g,"")
.replace(/","/g,"")
.replace(/"\/"/g,"")
.replace(/"#"/g,"");
cleanHeaderLine = cleanHeaderLine.replace(/,+$/, "");
console.log(cleanHeaderLine);
csv_lines[0] = cleanHeaderLine;
var newCsvLines = [];
csv_lines.forEach(function(line){
newCsvLines.push(line + "\n");
});
fs.writeFile('clean_file.csv', newCsvLines, function(err) {
if (err) throw err;
console.log('clean file saved');
});
I don't see any glaring errors here (maybe something with your regex? Not an expert on those) but this will solve your issue.
if (line.charAt(0) == ',') { line = line.substring(1); }
Adjust your variables accordingly. I don't think I have the same case as you.
EDIT: Here's a JSBin of it working.
http://jsbin.com/mirocedagi/1/edit?html,js,output

Photoshop Javascript script: Rename file and saveAs

Im new to using JS with photoshop and have some trouble. What I want to do is to get rid of the word "Online" in the file name of the current document and then save a JPG with new file name in a different folder.
With the help of the adobe reference I came up with the following script:
//Path where the final jpg should be saved
var JPGquality = 12;
var docPath="C:\Users\user\Desktop\test";
var docName='';
docName = activeDocument.name;
//Set new file name by replacing "_Online_" with "_"
var NewName = docName.replace("_Online_", "_");
var saveFile = new File(docPath+'/'+NewName+ '.jpg');
//Save JPG
function SaveJPEG(saveFile, jpegQuality) {
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpgSaveOptions.matte = MatteType.NONE;
jpgSaveOptions.quality = jpegQuality; //1-12
activeDocument.saveAs(saveFile, jpgSaveOptions, true,Extension.LOWERCASE);
}
The Script runs through but therewithout errors but nothing happens. It would be very helpful if someone could tell me what Ive done wrong. Hope someone helps me figuring out how to fix this ;)
I use this:
function saveAsJPG() {
jpgFile = new File(outputFolder + "/" + _CardFileName + ".jpg");
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpgSaveOptions.matte = MatteType.NONE;
jpgSaveOptions.quality = 12;
docRef.saveAs(jpgFile, jpgSaveOptions, true, Extension.LOWERCASE);
}
Try to use forward slashes in your docPath:
var docPath="C:/Users/user/Desktop/test";
\t (tab) and \u (beginning of a Unicode sequence) have special meanings in JS strings.
Or you can escape them, of course:
var docPath="C:\\Users\\user\\Desktop\\test";
The best way to write paths in javascript for photoshop automation is '/c/users/user/' That works on both mac and windows and you don't need to escape the backslashes

How can I write data in a single line on text file using javascript

I am trying to write data in a .txt file using JavaScript function.
My function :-
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("test.txt", true);
for(var j=1;j<9;j++)
{
if(document.getElementById('chk'+j).checked)
{
s.WriteLine(' ');
s.WriteLine(document.getElementById('item'+j).innerText);
s.WriteLine(',');
s.WriteLine(document.getElementById('txtBx'+j).value);
s.WriteLine(',');
s.WriteLine(document.getElementById('txtBxx'+j).value);
s.WriteLine(';');
}
}
alert("written");
s.Close();
}
Now the problem is that data being written on a new line.
(maybe because i am using s.WriteLine ?)
I want all the data to be written in a single line. how can i achieve this?
to elaborate more, my current output looks like this
abc
,
1
,
cdf
;
def
,
3
,
ehi
;
I want it like this-
abc,1,cdf;def,3,ehi;
Use s.write() instead of s.writeLine(). As the name implies, the second function is for writing whole lines, and it adds a newline after it.
Just add everything to a variable then write the line.
var st = document.getElementById('item'+j).innerText;
st += ','
st += document.getElementById('txtBx'+j).value;
s.WriteLine(st);

Categories