How to read javascript file as text file and prevent code to run multiple time
index.js
version = "1.001";
alert("JS run");
... other code ...
and I have html that use index.js
I try to read index.js by using
jQuery.get("js/index.js",function(data){
var currentVersion = data.split("\n")[0].split('"')[1];
}
I can read text as I want but alert("JS run") and other code inside also run after I use this code.
Related
I have the following interesting scenario in a Yeoman generator but I have to fall back on regular NodeJS file system operations.
In my case, I need first read and write a file that already exists on the file system. I read the file synchronously and I write the file synchronously.
function myFunction1(){
let content = fs.readFileSync('filename.txt', 'utf-8')
// change content in here
let newContent = content+"Hello World";
fs.writeFileSync('filename.txt', newContent);
}
In a later step, I need to read the same file again.
function myFunction2(){
let content = fs.readFileSync('filename.txt', 'utf-8')
}
The problem now is that the exact same file doesn't exist either in the filesystem or the code can access the file.
If I comment out the call for myFunction2 the file gets written to the file system.
However, I have a problem reading a file I changed before again. The question is:
Do I something wrong?
Is there anything I miss here?
Are there some workarounds my issue?
I sadly cannot refactor them to have just on call because of there different scenarios for writing and reading.
It seems like you have some typos and/or missing arguments in your function calls.
Try this:
function myFunction1(){
let content = fs.readFileSync('filename.txt', 'utf-8');
// create new file content to test writeFileSync logic
let newContent = content + ' something else';
fs.writeFileSync('filename.txt' , newContent );
}
function myFunction2(){
let content = fs.readFileSync('filename.txt', 'utf-8');
}
Hope this helps
I am using Evan plaice jquery-csv libary but I am running into a lot of trouble to get it working at the moment due to his code not updated after google code is deprecated.
I am using the one of his example where you upload a csv file and it will parse the document so that the csv file will be shown on the webpage Demo here.
I downloaded his code from github but then since the googlecode he imported is not working anymore I put the file jquery.csv.js in the same folder as the file I am using. In the jquery.csv.js, there is a function being called which is toArray in the html file. I deleted the line where it is used to be <script src="http://jquery-csv.googlecode.com/git/src/jquery.csv.js"></script> and added <script type="text/javascript" src="./jquery.csv.js"></script> However, for whatever reason it complains that toArry is not defined.
Basically the code is like this:
function printTable(file) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event){
var csv = event.target.result;
var data = $.csv.toArrays(csv); << The line that has problem.
var html = '';
for(var row in data) {
html += '<tr>\r\n';
for(var item in data[row]) {
html += '<td>' + data[row][item] + '</td>\r\n';
}
html += '</tr>\r\n';
}
$('#contents').html(html);
};
reader.onerror = function(){ alert('Unable to read ' + file.fileName); };
}
In the developer console it indicates:
Uncaught TypeError: Cannot read property 'toArrays' of undefined
at FileReader.reader.onload (file:///Users/Jace/Downloads/jquery-csv-master/examples/file-handling.html:75:25)
I think you're problem is that when you removed the reference to the jquery-csv library hosted on Google Code and included your local version, you put it above the reference to jQuery itself. That's when I notice the error you're describing. The order you load in your JavaScript files does matter. When for example JavaScript code in file B.js is depending on code in A.js, A.js needs to be specified before B.js.
So basically check if the order you're specifying the files in in your HTML file is correct:
<body>
<!-- HTML... -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="jquery.csv.js"></script> <!-- The "./" is not used here -->
<script>
// Code...
</script>
</body>
Also, the ./ in front is not needed and not common. I've never used it in any case. ;)
I hope that makes it a bit more clear to you!
I have two .html files (Intro.html and Main.html) sharing an external .js file.
My first .html file opens up the 2nd .html via a customized button and .online event from the external .js file using
document.getElementById("leaveButton").onclick = function () {
location = "Main.html";
}
My second .html file also has several buttons on its own page/window also being accessed by document.getElementById.onclick from the external .js file.
There are no problems and everything works fine if I keep separate .js files for each .html file.
However, when I have them share the same .js file, each .html page in the console complains about the other's document.getElementById("idName").onclick items. This is the error message I get,
Uncaught TypeError: Cannot set property 'onclick' of null
How do I resolve this using pure Javascript?
The simplest solution would be to only attempt to add the onclick() handler if the element exists. Something like:
if (!!document.getElementById("leaveButton")) {
document.getElementById("leaveButton").onclick = function () {
location = "Main.html";
}
}
I have a jsp file in which i am writing a function in javascript that takes as argument, a tar file name and returns a list of the file names of the files that the tar file contains.. How can it be done?
Have you tried using UnTar.js ? Its open source js library for that
edit :
providing usage example for clarity
function updateProgressBar(e) { ... update UI element ... }
function displayZipContents(e) { ... display contents of the file ... }
var unzipper = new bitjs.archive.Unzipper(zipFileArrayBuffer);
unzipper.addEventListener("progress", updateProgressBar);
unzipper.addEventListener("finish", displayZipContents);
unzipper.start();
some more info here
How to read text file (text1.txt) from current directory using javascript without jquery. I tried the following code.
var file = "text1.txt";
var reader = new FileReader();
var result = reader.readAsText(file);
console.log(result);
The FileReader API is usually used to read files selected via the an <input type="file">. It cannot read arbitrary files. The readAsText method expects to receive with a Blob or a File object, not a string containing a file name.
To read files that are siblings of the HTML document, use XMLHttpRequest. This will reliably work if you load the document over HTTP(S). If you are using a local HTML document (via a file: URI) then security restrictions in many browsers will prevent it from working (and you should run a local web server instead).
Option A, Your use-case prevents you from using an http or php server.
You can include local content in your javascript as a variable using a script include. If you are opening the page locally, as a file from a directory, this is the only way to include local content in the web page.
To include local content, put this above your other script tag:
<script src="text1.txt"></script>
and edit your text1.txt file so it assigns all the content to a variable:
gbl_text=`...contents of my text file...
...more contents...
...and so on....
`
You can use a script to create this include file, for example (use the ` tick mark below the tilde ~ key):
echo -n "var gbl_text=\`" > text1.txt
cat your-original-file.txt >> text1.txt
echo "\`" >> text1.txt
Then use the gbl_text variable in your javascript as needed...
function dosomething()
{
if (typeof(gbl_text)=='undefined'){
setTimeout('dosomething()',500) //call back until defined
}else{
console.log(gbl_text)
}
}
Option B, Your use-case would allow you to use the php-cli built-in server.
If you are able to run php-cli, you can open the page on the built-in php webserver, and read and write local content with a php call. To install and use php on linux,
sudo apt install php7.0-cli
#To use the php built-in webserver, run:
php -S localhost:8000 -t /path/to/your/content
So, instead of opening your html as a file, you would open as an http web page:
firefox http://localhost:8000/mypage.html
#or browser of choice
Now the local webpage is being served by an actual (local) http server with php support, and you can manipulate local files with it.
Here is simple example showing how to read and write to a local file using jQuery and php. Download and include jQuery (see jQuery.com) in your html file.
Contents of dofile.php:
<?php
$dowhat = $_REQUEST['dowhat'];
if ($dowhat=='save'){
$myvar = $_REQUEST['myvar'];
file_put_contents('myfile', $myvar);
}elseif($dowhat=='read'){
$myvar=file_get_contents('myfile');
echo $myvar;
}
?>
Contents of mypage.html:
<script src='jquery-3.2.1.js';></script>
<!--make sure the filename matches the jQuery you use-->
<script>
function savevar(){
var myvar=document.getElementById('mytxt').value
var path="dofile.php?dowhat=save&myvar="+myvar
$.get(path, function(data){
console.log("saved ...\n"+myvar)
alert("saved ...\n"+myvar)
});
}
function clearbox(){
document.getElementById('mytxt').value='reading file...'
setTimeout('getvar()',1000)
}
function getvar(){
var path="dofile.php?dowhat=read"
$.get(path, function(data){
console.log(data);
document.getElementById('mytxt').value=data
/*do other things with data here*/;
});
}
</script>
<html>
Type something in the text box.<br>
Use the Read and Write buttons to verify <br>
text is saved and read back.<br>
<input id='mytxt' value='type text here' onclick=document.getElementById('mytxt').value=''><br>
<input type='button' value='Save' onclick=savevar() ><input type='button' value='Read' onclick=clearbox() >
</html>
Please distinguish 2 kinds of reading files:
reading "from internet" - use XMLHttpRequest to read any kind of file
reading "from client" - use FileReader or <input type="file">
make a tiny iframe.
load the file there.
read it with iframe.innerHTML