How to add a file extension to file without any - javascript

so I've downloaded a few blank HTML files with no file extensions.
(I know these are HTML because if I manually add .HTML to the end and open the file, / the file contains html elements.... like etc.)
So they're located in my downloads folder. I'm simply trying to add a file extension to each of these files in the dir folder "download".
Here's my code:
var fs = require('fs');
var files = fs.readdirSync('C:/Users/Nikki/Downloads').forEach(file => {
console.log(file);
//There is a file named "desktop.ini", skip this file.
if (file === "desktop.ini") {
console.log("desktop file")
} else {
//not sure why it doesn't change the file extension. Maybe because there is none!?
var replaceExt = require('replace-ext');
var path = 'C:/Users/Nikki/Downloads/' + file;
var newPath = replaceExt(path, '.html');
console.log(newPath);
}
/*
fs.rename(file, file+'.html', () => {
console.log("\nFile Renamed!\n");
// doesnt work... either...
});
*/
});
How can I add the HTML file extension to each of these files?

If your file doesn't have a file extension, you can try the following code snippet :
var pos = file.lastIndexOf(".");
file = file.substr(0, pos < 0 ? file.length : pos) + ".html";

Related

Troubleshooting openDialog() Extendscript code

I'm trying to write an openDialog() extendscript code that filters the selectable file types to only csv files on a mac. I was directed to the code here which does what I'm asking:  Link
I've written mostly the same thing, and the panel opens and allows me to select a file, but for some reason the filter doesn't work.
Here's what I have written:
// target the active Premiere Pro project
var activeSequence = app.project.activeSequence;
// import the CSV file
var file = File.openDialog("Select a CSV file to import.", fileFilter);
if (file) {
file.open("r");
var data = file.read();
file.close();
}
//This is the filter used by the openDialog function
function fileFilter(file){
index = file.name.lastIndexOf(".");
ext = file.name.substring(index + 1);
if(ext == "xml" || ext == "XML"){
return true;
}
return false;
}
Can anyone see what the issue might be?
I just tried the code from the link and it works fine for me.
Here is my a bit shortened version of the same code:
var file = File.openDialog("Select a CSV file to import", fileFilter);
function fileFilter(file) {
if (!file instanceof Folder) return true;
if (file.name.split('.').pop().toLowerCase() == 'csv') return true;
return false;
}
Just in case, on Windows it works much simplier:
var file = File.openDialog("Select a CSV file to import.", "*.csv");

Using jQuery/javascript to dynamically add all images in a directory [duplicate]

I have a folder named "images" in the same directory as my .js file. I want to load all the images from "images" folder into my html page using Jquery/Javascript.
Since, names of images are not some successive integers, how am I supposed to load these images?
Works both localhost and on live server without issues, and allows you to extend the delimited list of allowed file-extensions:
var folder = "images/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
$("body").append( "<img src='"+ folder + val +"'>" );
}
});
}
});
NOTICE
Apache server has Option Indexes turned on by default - if you use another server like i.e. Express for Node you could use this NPM package for the above to work: https://github.com/expressjs/serve-index
If the files you want to get listed are in /images than inside your server.js you could add something like:
const express = require('express');
const app = express();
const path = require('path');
// Allow assets directory listings
const serveIndex = require('serve-index');
app.use('/images', serveIndex(path.join(__dirname, '/images')));
Use :
var dir = "Src/themes/base/images/";
var fileextension = ".png";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function (data) {
//List all .png file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='" + dir + filename + "'>");
});
}
});
If you have other extensions, you can make it an array and then go through that one by one using in_array().
P.s : The above source code is not tested.
This is the way to add more file extentions, in the example given by Roy M J in the top of this page.
var fileextension = [".png", ".jpg"];
$(data).find("a:contains(" + (fileextension[0]) + "), a:contains(" + (fileextension[1]) + ")").each(function () { // here comes the rest of the function made by Roy M J
In this example I have added more contains.
If interested in doing this without jQuery - here's a pure JS variant (from here) of the answer currently most upvoted:
var xhr = new XMLHttpRequest();
xhr.open("GET", "/img", true);
xhr.responseType = 'document';
xhr.onload = () => {
if (xhr.status === 200) {
var elements = xhr.response.getElementsByTagName("a");
for (x of elements) {
if ( x.href.match(/\.(jpe?g|png|gif)$/) ) {
let img = document.createElement("img");
img.src = x.href;
document.body.appendChild(img);
}
};
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
}
xhr.send()
Here is one way to do it. Involves doing a little PHP as well.
The PHP part:
$filenameArray = [];
$handle = opendir(dirname(realpath(__FILE__)).'/images/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
array_push($filenameArray, "images/$file");
}
}
echo json_encode($filenameArray);
The jQuery part:
$.ajax({
url: "getImages.php",
dataType: "json",
success: function (data) {
$.each(data, function(i,filename) {
$('#imageDiv').prepend('<img src="'+ filename +'"><br>');
});
}
});
So basically you do a PHP file to return you the list of image filenames as JSON, grab that JSON using an ajax call, and prepend/append them to the html. You would probably want to filter the files u grab from the folder.
Had some help on the php part from 1
$(document).ready(function(){
var dir = "test/"; // folder location
var fileextension = ".jpg"; // image format
var i = "1";
$(function imageloop(){
$("<img />").attr('src', dir + i + fileextension ).appendTo(".testing");
if (i==13){
alert('loaded');
}
else{
i++;
imageloop();
};
});
});
For this script, I have named my image files in a folder as 1.jpg, 2.jpg, 3.jpg, ... to 13.jpg.
You can change directory and file names as you wish.
Based on the answer of Roko C. Buljan, I have created this method which gets images from a folder and its subfolders . This might need some error handling but works fine for a simple folder structure.
var findImages = function(){
var parentDir = "./Resource/materials/";
var fileCrowler = function(data){
var titlestr = $(data).filter('title').text();
// "Directory listing for /Resource/materials/xxx"
var thisDirectory = titlestr.slice(titlestr.indexOf('/'), titlestr.length)
//List all image file names in the page
$(data).find("a").attr("href", function (i, filename) {
if( filename.match(/\.(jpe?g|png|gif)$/) ) {
var fileNameWOExtension = filename.slice(0, filename.lastIndexOf('.'))
var img_html = "<img src='{0}' id='{1}' alt='{2}' width='75' height='75' hspace='2' vspace='2' onclick='onImageSelection(this);'>".format(thisDirectory + filename, fileNameWOExtension, fileNameWOExtension);
$("#image_pane").append(img_html);
}
else{
$.ajax({
url: thisDirectory + filename,
success: fileCrowler
});
}
});}
$.ajax({
url: parentDir,
success: fileCrowler
});
}
This is the code that works for me, what I want is to list the images directly on my page so that you just have to put the directory where you can find the images for example -> dir = "images /"
I do a substring var pathName = filename.substring (filename.lastIndexOf ('/') + 1);
with which I make sure to just bring the name of the files listed and at the end I link my URL to publish it in the body
$ ("body"). append ($ ("<img src =" + dir + pathName + "> </ img>"));
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="jquery-1.6.3.min.js"></script>
<script>
var dir = "imagenes/";
var fileextension = ".jpg";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function (data) {
//Lsit all png file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.pathname, "").replace("http://", "");
var pathName = filename.substring(filename.lastIndexOf('/') + 1);
$("body").append($("<img src=" + dir + pathName + "></img>"));
console.log(dir+pathName);
});
}
});
</script>
</head>
<body>
<img src="1_1.jpg">
</body>
</html>
If, as in my case, you would like to load the images from a local folder on your own machine, then there is a simple way to do it with a very short Windows batch file. This uses the ability to send the output of any command to a file using > (to overwrite a file) and >> (to append to a file).
Potentially, you could output a list of filenames to a plain text file like this:
dir /B > filenames.txt
However, reading in a text file requires more faffing around, so I output a javascript file instead, which can then be loaded in your to create a global variable with all the filenames in it.
echo var g_FOLDER_CONTENTS = mlString(function() { /*! > folder_contents.js
dir /B images >> folder_contents.js
echo */}); >> folder_contents.js
The reason for the weird function with comment inside notation is to get around the limitation on multi-line strings in Javascript. The output of the dir command cannot be formatted to write a correct string, so I found a workaround here.
function mlString(f) {
return f.toString().
replace(/^[^\/]+\/\*!?/, '').
replace(/\*\/[^\/]+$/, '');
}
Add this in your main code before the generated javascript file is run, and then you will have a global variable called g_FOLDER_CONTENTS, which is a string containing the output from the dir command. This can then be tokenized and you'll have a list of filenames, with which you can do what you like.
var filenames = g_FOLDER_CONTENTS.match(/\S+/g);
Here's an example of it all put together: image_loader.zip
In the example, run.bat generates the Javascript file and opens index.html, so you needn't open index.html yourself.
NOTE: .bat is an executable type in Windows, so open them in a text editor before running if you are downloading from some random internet link like this one.
If you are running Linux or OSX, you can probably do something similar to the batch file and produce a correctly formatted javascript string without any of the mlString faff.
You can't do this automatically. Your JS can't see the files in the same directory as it.
Easiest is probably to give a list of those image names to your JavaScript.
Otherwise, you might be able to fetch a directory listing from the web server using JS and parse it to get the list of images.
In jQuery you can use Ajax to call a server-side script. The server-side script will find all the files in the folder and return them to your html file where you will need to process the returned information.
You can use the fs.readdir or fs.readdirSync methods to get the file names in the directory.
The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.
The second is synchronous, it will returns the file name array, but it will stop any further execution of your code until the read process ends.
After that you simply have to iterate through the names and using append function, add them to their appropriate locations. To check out how it works see HTML DOM and JS reference
Add the following script:
<script type="text/javascript">
function mlString(f) {
return f.toString().
replace(/^[^\/]+\/\*!?/, '');
replace(/\*\/[^\/]+$/, '');
}
function run_onload() {
console.log("Sample text for console");
var filenames = g_FOLDER_CONTENTS.match(/\S+/g);
var fragment = document.createDocumentFragment();
for (var i = 0; i < filenames.length; ++i) {
var extension = filenames[i].substring(filenames[i].length-3);
if (extension == "png" || extension == "jpg") {
var iDiv = document.createElement('div');
iDiv.id = 'images';
iDiv.className = 'item';
document.getElementById("image_div").appendChild(iDiv);
iDiv.appendChild(fragment);
var image = document.createElement("img");
image.className = "fancybox";
image.src = "images/" + filenames[i];
fragment.appendChild(image);
}
}
document.getElementById("images").appendChild(fragment);
}
</script>
then create a js file with the following:
var g_FOLDER_CONTENTS = mlString(function() { /*!
1.png
2.png
3.png
*/});
Using Chrome, searching for the images files in links (as proposed previously) didn't work as it is generating something like:
(...) i18nTemplate.process(document, loadTimeData);
</script>
<script>start("current directory...")</script>
<script>addRow("..","..",1,"170 B","10/2/15, 8:32:45 PM");</script>
<script>addRow("fotos-interessantes-11.jpg","fotos-interessantes-> 11.jpg",false,"","");</script>
Maybe the most reliable way is to do something like this:
var folder = "img/";
$.ajax({
url : folder,
success: function (data) {
var patt1 = /"([^"]*\.(jpe?g|png|gif))"/gi; // extract "*.jpeg" or "*.jpg" or "*.png" or "*.gif"
var result = data.match(patt1);
result = result.map(function(el) { return el.replace(/"/g, ""); }); // remove double quotes (") surrounding filename+extension // TODO: do this at regex!
var uniqueNames = []; // this array will help to remove duplicate images
$.each(result, function(i, el){
var el_url_encoded = encodeURIComponent(el); // avoid images with same name but converted to URL encoded
console.log("under analysis: " + el);
if($.inArray(el, uniqueNames) === -1 && $.inArray(el_url_encoded, uniqueNames) === -1){
console.log("adding " + el_url_encoded);
uniqueNames.push(el_url_encoded);
$("#slider").append( "<img src='" + el_url_encoded +"' alt=''>" ); // finaly add to HTML
} else{ console.log(el_url_encoded + " already in!"); }
});
},
error: function(xhr, textStatus, err) {
alert('Error: here we go...');
alert(textStatus);
alert(err);
alert("readyState: "+xhr.readyState+"\n xhrStatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to print all the txt files inside a folder using java script

I need to print all the txt files from a directory inside an HTML using javascript.
i tried to modify a code dealing with photos but I didn't success
How to load all the images from one of my folder into my web page, using Jquery/Javascript
var dir = "D:\Finaltests\test1\new\places";
var fileextension = ".txt";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function (data) {
//List all .txt file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<input type='file' onload='readText(" + dir + ")>");
});
}
});
You can use <input type="file"> with multiple attribute set, accept attribute set to text/plain; change event ;FileReader, for loop.
var pre = document.querySelector("pre");
document.querySelector("input[type=file]")
.addEventListener("change", function(event) {
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
(function(file) {
var reader = new FileReader();
reader.addEventListener("load", function(e) {
pre.textContent += "\n" + e.target.result;
});
reader.readAsText(file)
}(files[i]))
}
})
<input type="file" accept="text/plain" multiple />
<pre>
</pre>
You can also use webkitdirectory and allowdirs attributes for directory upload at chrome, chromium; at nightly 45+ or firefox 42+ where dom.input.dirpicker preference set to true, see Firefox 42 for developers , Select & Drop Files and/or Folders to be parsed. Note, you can also drop folders from file manager at <input type="file"> element
var pre = document.querySelector("pre");
document.querySelector("input[type=file]")
.addEventListener("change", function(event) {
console.log(event.target.files)
var uploadFile = function(file, path) {
// handle file uploading
console.log(file, path);
var reader = new FileReader();
reader.addEventListener("load", function(e) {
pre.textContent += "\n" + e.target.result;
});
reader.readAsText(file)
};
var iterateFilesAndDirs = function(filesAndDirs, path) {
for (var i = 0; i < filesAndDirs.length; i++) {
if (typeof filesAndDirs[i].getFilesAndDirectories === 'function') {
var path = filesAndDirs[i].path;
// this recursion enables deep traversal of directories
filesAndDirs[i].getFilesAndDirectories()
.then(function(subFilesAndDirs) {
// iterate through files and directories in sub-directory
iterateFilesAndDirs(subFilesAndDirs, path);
});
} else {
uploadFile(filesAndDirs[i], path);
}
}
};
if ("getFilesAndDirectories" in event.target) {
event.target.getFilesAndDirectories()
.then(function(filesAndDirs) {
iterateFilesAndDirs(filesAndDirs, '/');
})
} else {
// do webkit stuff
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
(function(file) {
uploadFile(file)
}(files[i]))
}
}
})
<!DOCTYPE html>
<html>
<head>
<script></script>
</head>
<body>
<input type="file" webkitdirectory allowdirs directory />
<pre>
</pre>
</body>
</html>
plnkr http://plnkr.co/edit/Y1XYd9rLOdKRHw6tb1Sh?p=preview
For ajax requests at chromium, chrome file: protocol local filesystem you can launch with --allow-file-access-from-files flag set, see Jquery load() only working in firefox?.
At firefox you can set security.fileuri.strict_origin_policy to false, see Security.fileuri.strict origin policy.
For a possible $.ajax() approach at chrome, chromium you can try
var path = "/path/to/drectory"; // `D:\`, `file:///`
var files = [];
$.ajax({url:path, dataType:"text html"})
.then((data) => {
// match file names from `html` returned by chrome, chromium
// for directory listing of `D:\Finaltests\test1\new\places`;
// you can alternatively load the "Index of" document and retrieve
// `.textContent` from `<a>` elements within `td` at `table` of
// rendered `html`; note, `RegExp` to match file names
// could probably be improved, does not match space characters in file names
var urls = $.unique(data.match(/\b(\w+|\d+)\.txt\b/g));
return $.when.apply($, $.map(urls, (file) => {
files.push(file);
// `\`, or `/`, depending on filesystem type
return $.ajax({url:path + "/" + file
, dataType:"text html"})
.then((data) => {
// return array of objects having property set to `file` name,
// value set to text within `file`
return {[file]:data}
})
}))
})
.then((...res) => {
console.log(res, files)
})
you can't reach the host filesystem with javascript for security reason.
The best you can do is to make a single ajax call to a server-side script (php for exemple) that will collect all html file and return them to your ajax call.
gethtml.php:
<?php
$output = "";
// your list of folders
$folders = [
'D:\Finaltests\test1\new\places1',
'D:\Finaltests\test1\old\places2',
'D:\Finaltests\test1\whatever\places3'
];
foreach ($folders as $key => $dir) {
if(!is_dir($dir))
continue;
// get all files of the directory
$files = scandir($dir);
foreach ($files as $file) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if(finfo_file($finfo, $file) == 'text/plain')
$output .= file_get_contents($dir . DIRECTORY_SEPARATOR . $file);
}
}
echo $output;
exit;
?>
Ajax call:
$.get('path/to/gethtml.php', function(response){
$('body').html(response);
});
you can change the line of php that check the mime type according to the type of the file you want to get (plain text or text/html or whatever)

How to download the content/image/data of input type file?

I wanna know how to download the data/content/image in an input type file
Note: It doesnt have to be submitted. just a direct download from a button in which he can be able to download the content of an input type file
How can i do this?
sample code
$(".downloadupinvoice").click(function(){
var file = document.getElementById('id-input-file-2').files[0];
//Put some code here to produce a file ?
window.location=window.URL.createObjectURL(file);
})
i cant seem to preview the file but it is not downloading also i notice in the address bar that it display like this
blob:69c7ee1a-ba44-4234-9216-68b3c86b9c96
Finally got it.
$(".downloadupaddinvoice").click(function(){
var filename = $('#id-input-file-2').val();
if (filename == "" || filename == null) {
alert('Error');
}else {
var file = document.getElementById('id-input-file-2').files[0];
var filename = document.getElementById('id-input-file-2').files[0].name;
var blob = new Blob([file]);
var url = URL.createObjectURL(blob);
$(this).attr({ 'download': filename, 'href': url});
filename = "";
}
})
This is the where the anchor tag :)
<a class="help-button col-sm-4 downloadupaddinvoice" title="Download uploaded invoice" download><i class="icon-download-alt"></i></a>
Hope it might help in the future..

More efficient way to async load javascript files

I am trying to load file files asynchronously with javascript, here is the code:
var jsFiles = [ 'js/enscroll.min.js',
'js/jp_custom.js',
'js/jquery.uploadifive.js',
'js/raphael-min.js',
'js/pgloader.js',
'js/jquery.custom.js' ];
for( var i=0, j=jsFiles.length; i < j; i++ ){
var file = jsFiles.shift();
asyncLoader(file, i);
}
function asyncLoader( filename, position, fileType ){
var type = typeof fileType == "undefined" ? "script" : fileType,
resource = document.createElement(type),
script = document.getElementsByTagName(type)[position+1];
resource.src = filename;
resource.type = "text/javascript";
script.parentNode.insertBefore(resource, script);
}
i am useing this code under the <head></head> tag means in the top of the file, and here is how do used the files related functionalities:
$(function(){
$(window).load(function(){
// Start to use the related files
});
})
at the bottom of the page so that after load the window my files working properly, i just want to know is this the best way to reduce the page load time(only javascript)? or what i have to with it to make it more efficient?

Categories