I would like to add an entire folder of files to my package. Instead of adding each file individually, is it possible to add an entire folder of files using api.add_files in the package.js file? Perhaps something like:
Package.on_use(function(api) {
api.add_files(["files/*","client");
});
I don't think there's something like that currently in the public API.
However, you can use plain old Node.JS to achieve what you want to do.
Our package structure looks like this :
/packages/my-package
|-> client
| |-> nested
| | |-> file3.js
| |-> file1.js
| |-> file2.js
|-> my-package.js
|-> package.js
We build a helper function as follow :
function getFilesFromFolder(packageName,folder){
// local imports
var _=Npm.require("underscore");
var fs=Npm.require("fs");
var path=Npm.require("path");
// helper function, walks recursively inside nested folders and return absolute filenames
function walk(folder){
var filenames=[];
// get relative filenames from folder
var folderContent=fs.readdirSync(folder);
// iterate over the folder content to handle nested folders
_.each(folderContent,function(filename){
// build absolute filename
var absoluteFilename=folder+path.sep+filename;
// get file stats
var stat=fs.statSync(absoluteFilename);
if(stat.isDirectory()){
// directory case => add filenames fetched from recursive call
filenames=filenames.concat(walk(absoluteFilename));
}
else{
// file case => simply add it
filenames.push(absoluteFilename);
}
});
return filenames;
}
// save current working directory (something like "/home/user/projects/my-project")
var cwd=process.cwd();
// chdir to our package directory
process.chdir("packages"+path.sep+packageName);
// launch initial walk
var result=walk(folder);
// restore previous cwd
process.chdir(cwd);
return result;
}
And you can use it like this :
Package.on_use(function(api){
var clientFiles=getFilesFromFolder("my-package","client");
// should print ["client/file1.js","client/file2.js","client/nested/file3.js"]
console.log(clientFiles);
api.add_files(clientFiles,"client");
});
We simply use Node.JS fs utils to work with the file system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With