JS Get properties from many files at once - javascript

What I have: 50 mp3 files in a folder.
What I want to do: Create an object for every file that includes name and src.
What I don't know how to do is select and get properties from all of the files. Is it even possible? I know that you can get info from a text file via JS.
It would maybe be something like:
for (var i = 0; i < musicFolder.length; i++) {
var object = new Object (
musicFolder[i].title,
musicFolder[i].path/src
);
objectArray.push(object);
}
I would perhaps need to select an entire folder, but I dont know how to do this is JS.

Assuming that you are running this in Node.js and you only need the name and the path of the file, you can do this:
var fs = require('fs');
path = 'your path here';
const res = [];
fs.readdir(path, (err, items) => {
for (var i=0; i<items.length; i++) {
res.push({
name: items[i],
src: `${path}/${items[i]}`
});
}
console.log(res)
});
This will iterate your folder and list all the files in it. Then it will save the name of the file and its path in a object and push it to an array.

Related

Default HTML File manager

So I noticed when you put the path of your folder in a browser you get a default file manager.
I wanted to ask how could I manipulate the default changes in the path? Not just only the file manager but also the paths of other files, so I could parse them through a .md parser.
I tried fetching the data of the API that looked like a lot of work and I think there is a easier way to do this, because if there is a default way it generates the file manager I can just modify that.
In the end I couldn't really change the design of the main file system so I just extracted the elements and appended it to the the main HTML file.
fetch(`./Posts/`)
.then((response) => response.text())
.then((data) => {
//Parse the data to html
var parser = new DOMParser();
var posts = parser.parseFromString(data, "text/html");
// Get the files
var files = posts.querySelector("ul");
var li = files.querySelectorAll("li");
var content = document.querySelector("main");
//Seperate titles and push them in a array
var list = [];
for (var i = 0; i < li.length; i++) {
var text = li[i].innerText;
//split the innerText from ".md"
var titles = text.split(".md");
var title = titles[0];
list.push(title);
var name = li[i].getElementsByClassName("name");
//change the innerHTML of the "name" span's
name.item(0).innerHTML = title;
content.append(li[i]);
}
});

Trying to create a Google Drive Script to copy and move files

I'm horrible at coding so I'm sure this will need some work.
My Problem: My company does work for a lot of other companies (example Drive hierarchy photo attached). Each company we work with gets their own folder that is nested under the folder 'Shirts for other companies". We put all their assets into these folders (logos, mocks, quotes).
We want to build a script that will look into the individual company folders and take any file that starts with the word Mock and automatically copy it and put it into the database folder found in the picture below.
Here is the script have so far. but I'm having trouble getting into the subfolders (ford tshirts and designs). Not only that, but if it runs everyday the script will keep duplicating the files it has duplicated in the past which I want to avoid.
Script:
Function getTheFiles() {
var dApp = DriveApp;
var folderIter = dApp.getFolderByName("Shirts for other companies");
var folder = folderIter.next();
var filesIter = folder.getFiles();
var dataBase = folder.getFoldersByName("database1").next();
var i = 1;
while(filesIter.hasNext()) {
var file = filesIter.next();
var filename = file.getName();
if(filename = "mocking") {
file.makeCopy(dataBase);
}
logger.log(filename);
i++;
}
If I understood you correctly, you want to:
Copy all files from the different subfolders inside a folder called "Shirts for other companies", that start with the word mock, to the Database folder (which is also inside the main folder).
Avoid files getting copied many times.
If that's the case, you could do the following:
Search for all files in each subfolder of the main folder that start with mock, excluding the files inside Database folder. For this, you iterate through all files in each subfolder (after checking the subfolder is not named Database folder. For each file, you check that the name start with mock, using the method substring.
To keep track of which files are copied, and so avoid making duplicates, you can use PropertiesService, which can store key-value pairs. The id of every copied file is copied to the script property, and then, the next time the script runs, it checks whether the id is in the property. If that's the case, the file doesn't get copied again. One thing to notice is that script properties can only store strings, so that arrays have to be converted to a string every time we want to store a new id (via toString, and back to an array, via split.
The function below does all these things (check inline comments for more details):
function copyFiles() {
var mainFolder = DriveApp.getFoldersByName("Shirts for other companies").next();
var folders = mainFolder.getFolders(); // Get folder iterator from main folder
var databaseFolderName = "Database folder"; // You database folder name
var databaseFolder = mainFolder.getFoldersByName(databaseFolderName).next(); // Get databse folder
var idsArray = []; // Array to store the ids of the copied files
while (folders.hasNext()) { // Iterate through each folder in the main folder
var folder = folders.next();
if (folder.getName() !== databaseFolderName) { // Check current folder is not the database folder
var files = folder.getFiles();
while (files.hasNext()) { // Iterate through each file in each subfolder
var file = files.next();
if (file.getName().substring(0, 4).toLowerCase() === "mock") { // Check that file name starts with "mock"
// Get ids of the files that were copied in previous executions:
var key = "copied-ids";
var scriptProperties = PropertiesService.getScriptProperties();
var ids = scriptProperties.getProperty(key);
if (ids) idsArray = ids.split(",");
else ids = "";
// Get current file id:
var id = file.getId();
// Check that current file id is not in properties (not copied before):
if (idsArray.indexOf(id) === -1) {
file.makeCopy(databaseFolder); // Copy file to database folder
idsArray.push(id); // Add file id to the array of copied files
}
ids = idsArray.toString();
scriptProperties.setProperty(key, ids);
}
}
}
}
}
Reference:
PropertiesService
String.prototype.substring()
Array.prototype.toString()
String.prototype.split()
I hope this is of any help.
This function would search your entire Google Drive for files starting the the letter Mock and put Name, url, id, type (folder or file) into the active spreadsheet and tab named MoclList;
function getAllMocks() {
var ss=SpreadsheetApp.getActive();
var sh1=ss.getSheetByName('MocksList');
sh1.clearContents();
sh1.appendRow(['Name','Url','Id','Type']);
getFnF();
SpreadsheetApp.getUi().alert('Process Complete')
}
var level=0;
function getFnF(folder) {
var folder= folder || DriveApp.getRootFolder();
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('MocksList');
var files=folder.getFiles();
while(files.hasNext()) {
var file=files.next();
if(file.getName().toLowerCase().slice(0,4)=='mock') {
var firg=sh.getRange(sh.getLastRow() + 1,level + 1);
firg.setValue(file.getName());
firg.offset(0,1).setValue(Utilities.formatString('=HYPERLINK("%s","%s")',file.getUrl(),'FILE: ' + file.getName()));
firg.offset(0,2).setValue(file.getId());
firg.offset(0,3).setValue('File');
}
}
var subfolders=folder.getFolders()
while(subfolders.hasNext()) {
var subfolder=subfolders.next();
var forg=sh.getRange(sh.getLastRow() + 1,level + 1);
forg.setValue(subfolder.getName());
forg.offset(0,1).setValue(Utilities.formatString('=HYPERLINK("%s","%s")',subfolder.getUrl(),'FOLDER: ' + subfolder.getName()));
forg.offset(0,2).setValue(subfolder.getId());
forg.offsert(0,3).setValue('Folder');
//level++;
getFnF(subfolder);
}
//level--;
}

Send to Trash with JXA on Mac OS

So I have been looking for an answer to this and have had no luck. Is it possible to send a file to the trash using JXA in Mac Automation? my simple test code looks like this:
// set startup applications that this script will use
var app = Application.currentApplication()
var finder = Application("Finder");
app.includeStandardAdditions = true
function openDocuments(droppedItems)
{
// Variables
var AllFiles = [] // array to store all files in.
for (var item of droppedItems)
{
AllFiles.push(item) // load each file into array
}
// go through each file in the list
for (var i = 0; i < AllFiles.length; i ++)
{
// move to the trash
finder.move(Path(AllFiles[i]), {
to: Path("/Users/usr/.trash"),
replacing: true
})
}
}
this is just a test I am building that should send whatever file I drop onto it to the trash, but it does not recognize .trash as a valid folder location. I have tested it with other folder and that does work so I am assuming that .trash is locked.
I think you need a reference to the trash folder via pathTo command of Standard Additions
For example, to send the currently selected file in the Finder to the Trash, something like this could work.
(() => {
const
ca = Application.currentApplication(),
sa = (ca.includeStandardAdditions = true, ca),
app = Application('Finder'),
seln = app.selection();
app.delete(seln[0])
})();

how to get pdf context into html?

for several days now I'm learning html, CSS and now javascript. What I need is a way to get the informations of an pdf document into my html webpage.
I tried several things now and couldnt find the correct answer or informations I need. So here come an use case:
get an .pdf document into a folder
get the information of all .pdf documents of the target folder (with the exact same formatting)
convert those information into html context
get this html context to show on the webpage (images and text)
1 is trivial, I can just drag and drop my documents
2 I'm thinking about something like an array, which then calls the folder to get data into it.
For this I found:
'use strict';
function getFiles(dir) {
fileList = [];
var files = fs.readdirSync(dir);
for (var i in files) {
if (!files.hasOwnProperty(i)) continue;
var name = dir + '/' + files[i];
if (!fs.statSync(name).isDirectory()) {
fileList.push(name);
}
}
return fileList;
}
console.log(getFiles('pathtodirectory'));
Here I'm always getting a reference error, no matter what the path, well I can use only a local path on my pc for now. I'm not 100% sure what everything does, but I think I got it good so far. This function just gets me a list of the documents to work with.
3 That's even more tricky for me now, but I think if I get the data to work with, I may be able to work something out.
4 I think I can do it with a little research
I am happy for any tips or solutions, as I said I'm quite new to all of this :)
regards,
Pascal
'use strict';
function getFiles(dir) {
fileList = []; // <- This becomes a global variable
Should be:
'use strict';
function getFiles(dir) {
var fileList = []; // <- Now it's local to this scope
Because creating implicit global variables are not allowed in strict mode.
Also the getDirSync return an array, so you should treat it as such:
function getFiles(dir) {
fileList = [];
var files = fs.readdirSync(dir);
for (var i = 0; i < files.length; i++) {
var name = dir + '/' + files[i];
if (!fs.statSync(name).isDirectory()) {
fileList.push(name);
}
}
return fileList;
}
Or with .reduce:
function getFiles(dir) {
return fs.readdirSync(dir).reduce(function(arr, file) {
var name = dir + '/' + file;
if (!fs.statSync(name).isDirectory()) {
arr.push(name);
}
return arr;
}, []);
}

Reading all files in a directory

here is the code snippet of what I am working with right now...
/*
Module: inputReader.js, directoryScanner.js (included)
Description: Basic file reader returns string of contents of a file from a set file name
Needs to be done: Add key listener to allow for a dynamic file name
*/
// Declare node.js module dependencies from API
var fs = require('fs'),
wrench = require('wrench'),
util = require('util')
// Define module to be exported as a function(s)
module.exports = {
dirRead: function() {
var rootfolder = './node_modules';
var filteredfiles = [];
var files = [];
var fileextension = '.html';
files = wrench.readdirSyncRecursive(rootfolder)
for (var i = 0; i<files.length; i++) {
if (files[i].indexOf(fileextension) != -1) {
filteredfiles.push(files[i]);
}
}
return filteredfiles;
},
fileRead: function() {
// Call synchronous fileSystem function readFileSync on file name
for(i = 0; i<filteredfiles.length; i++) {
var temp = fs.readFileSync(filteredfiles[i].toString(), 'utf8')
return temp
}
}
};
I am exporting a module of 2 different functions; the first (readDir) that reads a directory and its' subdirectories for a list of files and the second (readFile) which relies on the first (reads the list of files from the first function and actually goes through each file).
The problem is when I try to call that look of filteredfiles in the 2nd function, readFile, I get an error saying filteredfiles is undefined.
I am not sure how to fix this, may someone help me please? (My guess is a scope problem)...
res.send(reader.dirRead()) and then, res.send(reader.fileRead(reader.dirRead()))
filteredfiles is declared locally in dirRead function (so it is not visible for fileRead function). You must declare it in some higher scope, or pass it as a fileRead parameter.

Categories