google appscript to move folder content to another folder - javascript

I am new at this and not programmer or a coder.
I am trying to make google app script to move folder content to another folder in google drive
I came across this link
I am using below code and it runs without error, but the files are not moved.
function myFunction() {
var source_folder = DriveApp.getFolderById('1fMCHA4-b2a2BQjO0VD2dd5m4V5WvXz9D')
var dest_folder = DriveApp.getFolderById('1LbZchJflfcnOKqSPYCdGcFTI_7AAVJIi')
function moveFiles(source_folder, dest_folder){
var files = source_folder.getFiles();
while (files.hasNext()) {
var file = files.next();
dest_folder.addFile(file);
source_folder.removeFile(file);
}
}
}
Can someone advise.

Try:
function myFunction() {
const source_folder = DriveApp.getFolderById('1fMCHA4-b2a2BQjO0VD2dd5m4V5WvXz9D')
const dest_folder = DriveApp.getFolderById('1LbZchJflfcnOKqSPYCdGcFTI_7AAVJIi')
// Call the function:
moveFiles(source_folder, dest_folder)
function moveFiles(source_folder, dest_folder) {
const files = source_folder.getFiles()
while (files.hasNext()) {
const file = files.next()
file.moveTo(dest_folder)
}
}
}
Rather than copy and delete each file, just move it!
The main problem you had was that you were not calling your function. You had only defined it.
Learn More:
File.moveTo()

Similar to the first answer but uses the Drive API to perform the move
function movefiles() {
const sfldr = DriveApp.getFolderById('sid');
const dfldr = DriveApp.getFolderById('did');
const files = sfldr.getFiles()
while (files.hasNext()) {
const file = files.next()
Drive.Files.update({ "parents": [{ "id": dfldr.getId() }] }, file.getId(), null, { supportsAllDrives: true });
}
}
Drive.Files.update

Related

Trying to import all google sheets files within a folder to a spreadsheet, all column headers are the same

I need to be able to take all files from a a folder within drive and input the data into the spreadsheet. I am also creating a Menu Tab so I can just Run the script without going to editor. It would be great if I can create a way enter names of existing folder name without always going to the script in order to take out that extra step. This is the script I am using. I really need assistance with this.
function importTimesheets() {
var spreadsheets = DriveApp.
getFolderById("").
getFilesByType(MimeType.GOOGLE_SHEETS);
var data = [];
while (spreadsheets.hasNext()) {
var currentSpreadsheet = SpreadsheetApp.openById(spreadsheets.next().getId());
data = data.concat(currentSpreadsheet
.getSheetByName('Timesheet')
.getRange("A3:L10")
.getValues()
);
}
SpreadsheetApp.
getActiveSheet().
getRange(1, 1, data.length, data[0].length).
setValues(data);
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Generate Timesheets')
.addItem('Generate', 'importTimesheets')
As far as I understand you are trying to find a solution for this line of code, whereby you currently have to enter the Id manually.
DriveApp.getFolderById("")
My suggestions would be to prompt the user for the folder Id, because prompting for the folder name may cause errors if more than one folder has the same name. My suggestion is implemented as follows:
const folderId = SpreadsheetApp.getUi().prompt("Please enter the Folder Id").getResponseText()
const folder = DriveApp.getFolderById(folderId)
You could also use the Google File/Folder picker, as described here to search and select the folder.
Try this:
var level=0;
function getFnF(folder = DriveApp.getRootFolder()) {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet1')
const files=folder.getFilesByType(MimeType.GOOGLE_SHEETS);
while(files.hasNext()) {
let file=files.next();
let firg=sh.getRange(sh.getLastRow() + 1,level + 1);
firg.setValue(Utilities.formatString('File: %s', file.getName()));//need editing
}
const subfolders=folder.getFolders()
while(subfolders.hasNext()) {
let subfolder=subfolders.next();
let forg=sh.getRange(sh.getLastRow() + 1,level + 1);
forg.setValue(Utilities.formatString('Fldr: %s', subfolder.getName()));//needs editing
level++;
getFnF(subfolder);
}
level--;
}
function runThisFirst() {
let r = SpreadsheetApp.getUi().prompt('Folder id','Enter Folder Id',SpreadsheetApp.getUi().ButtonSet.OK);
let folder = DriveApp.getFolderById(r.getResponseText())
getFnF(folder);
}

Async and Sync Functions Node JS

I have a couple of functions I am running to download a zip file from Nexus, then unzip/extract the contents of the zip file, finally a search for a specific file type. All function work, however the synchronous search for some reason is not producing any results. If I simply run the download and extract functions in 1 script, then execute the search in another script I get my expected results. I am almost positive it is due to the search being synchronous whereas the download and extract are both async. Is there a quick way to add the find function at the end after the download & extract functions have run? Below is the code:
//npm modules
const fs = require('fs-extra');
const download = require('download');
const unzipper = require('unzipper');
const path = require('path');
//Custom Variables
const artifact = 'SOME_FILE.zip';
const repo = "SOME NEXUS REPOSITORY";
const url = "http://SOME URL/repository/";
const directory = 'SOME DIRECTORY';
//Get Artifact and Extract it to local directory function
const getArtifact = async () => {
const getArtifact = await download(url+repo, "./unzip")
const file = await fs.writeFileSync(directory+artifact, await download(url+repo))
const readStream = await fs.createReadStream(directory + artifact).pipe(unzipper.Extract({path:
directory}))
}
//Find function which should run after download and extract have been fulfilled
const findFile = function (dir, pattern) {
var results = [];
fs.readdirSync(dir).forEach(function (dirInner) {
dirInner = path.resolve(dir, dirInner);
var stat = fs.statSync(dirInner);
console.log(stat)
if (stat.isDirectory()) {
results = results.concat(findFile(dirInner, pattern));
}
if (stat.isFile() && dirInner.endsWith(pattern)) {
results.push(dirInner);
}
});
console.log(results)
return results;
};
//clear contents of directory before new download and extract
fs.emptyDirSync(directory)
//call download and extract function
getArtifact()
When I run "findFile" after the download & extract by itself in a separate script I get expected array output. However, when I try to incorporate (see below) this into the same script I get the an empty array:
getArtifact().then(function findFile (dir, pattern) {
var results = [];
fs.readdirSync(directory).forEach(function (dirInner) {
dirInner = path.resolve(directory, dirInner);
var stat = fs.statSync(dirInner);
console.log(stat)
if (stat.isDirectory()) {
results = results.concat(findFile(dirInner, pattern))
if (stat.isFile() && dirInner.endsWith(pattern)) {
results.push(dirInner);
}
}
console.log(results)
return results;
})
})
//Output
[]
//If I try the following:
getArtifact().then(findFile(directory, file))
// I get same empty array
[]
//If I run "findFile" in its own script after the download extract I get the following:
[
'SOME_FILE_PATH\\document1',
'SOME_FILE_PATH\\document2',
'SOME_FILE_PATH\\document3',
'SOME_FILE_PATH\\document4',
'SOME_FILE_PATH\\document5',
'SOME_FILE_PATH\\document6',
'SOME_FILE_PATH\\document7
]
Any help with how I can incorporate my findFile function into my existing download&extract function is appreciated...

How to use "require" dynamically in javascript?

I have a javascript function in "sample.js" file. It is like this:
var mapDict = { '100': 'test_100.js', '200': 'test_200_API.js', '300': 'test_300_API.js' }
function mapAPI()
{
this.version = 0.1;
}
mapAPI.prototype.getFileName = function( id ) {
return mapDict[id]
}
module.exports = mapAPI;
in another file named "institute.js" I want to require the above "test_xxx_API" files dynamically. I have the following code:
const mapAPI = require('../../sample.js');
const map = new mapAPI();
const mapFile = map.getFileName("100");
var insAPI = require(mapFile);
When I run this code by "node institute.js" command, I get the following error:
Error: Cannot find module './test_100_API.js'.
But the "test_100_API.js" file exists and is located in the current folder besides "institute.js". When I changed var insAPI = require(mapFile); to var insAPI = require("./test_100_API.js"); and give it the exact path instead of dynamic path, it works fine. Can anyone help me?
Thanks in advance

Move Files in google script

i use the function MoveFiles() to copy file into other folder.
But when i ran it, i try to delete the file in the original folder. After deleted it, i saw that the file that i moved also deleted.
How to make the file that i moved not be deleted too?
Tqvm
function MoveFiles() {
var SourceFolder = DriveApp.getFolderById('1WIZxuF_r9I-510Kfw9N0AImcS1Uf63dC');
var SourceFiles = DriveApp.getFolderById('1QfFl5JIfOYaTXZyFpuBNSMzBdBrXLll9').getFiles();
var DestFolder = DriveApp.getFolderById('1_03PnkJlt6mTo5bAExUMOdZVVkzMAUsA');
while (SourceFiles.hasNext()) {
var file = SourceFiles.next();
DestFolder.addFile(file);
SourceFolder.removeFile(file);
}
}
Try switching the code line for delete and add. According to this related SO post:
I've found that I needed to reverse the last two lines (so the removeFile is done first) otherwise the removeFile actually just removes it from the folder it was just added to and not from the original parent.
I've tested it and actually get the correct result, here is my code snippet:
function myFunction() {
var folder = DriveApp.getFolderById('sourceID');
var destinationFolder = "destinationID";
var contents = folder.getFiles();
while (contents.hasNext()){
var file = contents.next();
moveFiles(file.getId(),destinationFolder);
}
}
function moveFiles(sourceFileId, targetFolderId) {
var file = DriveApp.getFileById(sourceFileId);
file.getParents().next().removeFile(file);
DriveApp.getFolderById(targetFolderId).addFile(file);
}
Hope this helps.

Angular 2 + Firebase Push Function

I currently have completed a tutorial which reads/writes to a Firebase using Angular2.
Need some help with the below function within the firebase.service.ts
addListing(listing){
let storageRef = firebase.storage().ref();
for (let selectedFile of [(<HTMLInputElement>document.getElementById('image')).files[0]]){
let path = `/${this.folder}/${selectedFile.name}`;
let iRef = storageRef.child(path);
iRef.put(selectedFile).then((snapshot) => {
listing.image = selectedFile.name;
listing.path = path;
return this.listings.push(listing);
});
}
}
Code that runs the function
Within the add-listing.component.html file
<form (submit)="onAddSubmit()">
Within the add-listing.component.ts file
onAddSubmit(){
let listing = {
title:this.title,
city:this.city,
owner:this.owner,
bedrooms:this.bedrooms,
price:this.price,
type:this.type
}
this.firebaseService.addListing(listing);
this.router.navigate(['listings']);
}
This all works correctly - however I want to change the function to allow data to be pushed to the database without having to upload a image or file - currently the function wont run unless a image is included in the form.
Thanks for all your help.

Categories

Resources