0

I realize that JavaScript is not usually used to copy folders or files, but I'm using a wsf file written in JavaScript for use only on my local system.

I'll give a simplified explanation of the problem I have: I have a folder C:/Program Files/Folder, which has three files in it, File1, File2, and File3. I want to copy only File1 and File2, because File3 is unnecessary for me to copy, and is in use by another process which cannot be killed. (In reality I have a folder with hundreds of files, and I want to copy all of them except for one or two.) Aside from initializing each file and doing fso.fileCopy() on each individual file, is there some way to copy the entire folder, excluding File3? Some kind of exclusion list maybe?

What I have:

var fso = new ActiveXObject("Scripting.FileSystemObject");

var originalFolder = fso.GetFolder("C:\\Program Files\\Folder");
originalFolder.Copy("D:\\Program Files\\Folder");

This would crash, since File3 is in use by a process. I don't want to have to do

var file1 = fso.getFile("C:\\Program Files\\Folder\\File1");
file1.Copy("D:\\Program Files\\Folder\\File1");
var file2 = fso.getFile("C:\\Program Files\\Folder\\File2");
file2.Copy("D:\\Program Files\\Folder\\File2");

for hundreds of files.

I am very new to scripting, so I'm not even sure if it's possible to do something like this in JavaScript.

Jesse
  • 8,605
  • 7
  • 47
  • 57
Michael C
  • 33
  • 2
  • 4
  • Some of the answers on [this question](http://stackoverflow.com/questions/10769034/file-management-in-javascript) might be helpful? – Ren Apr 30 '13 at 00:48
  • meh, flashback of my VBA days. If I were you I'd search for the example in VB, VBA, VBScript and translate it to JS. The calls to the FileSystemObject COM object will be much the same. – MatthewMartin Apr 30 '13 at 02:25

3 Answers3

0

Javascript supports try { ... } catch (exception) { ... } blocks. While I would highly recommend a language more suited to this sort of local scripting task (Perl, Ruby, Python, and many more), it is possible for you to wrap your file.Copy() call in a try-catch block, catch the exception for files in use, and proceed without having the entire thing crash.

More information on Javascript try-catch blocks here.

Maggy May
  • 233
  • 1
  • 7
  • Ah, thank you! This is a wonderful idea, and I'm a bit embarrassed that I didn't think of it myself! :) – Michael C Apr 30 '13 at 08:45
0

It is possible using Node.js (and maybe other JS Frameworks, but I only use Node so I don't know about the others)

var fs = require('fs');
fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));
Datsik
  • 14,453
  • 14
  • 80
  • 121
-1
I am very new to scripting, so I'm not even sure if it's possible to do something like this in javascript.

It isn't. If javascript could do that, your computer would have 10 billion files containing spam copied to your file system every time you surfed the internet.

7stud
  • 46,922
  • 14
  • 101
  • 127