I'm trying to make a help command that when you use it, instead of having to manually type all the commands, how would I do that? like if I do !help utility how would I grab the utility folder and then get all the commands and list it? i've been trying fs but its confusing with how you would get directs. any help?
You're on the right track with using fs
const fs = require('fs')
// check if that folder exists
if (!fs.existsSync(`../../commands/${args[0]}`))
return message.channel.send('That folder does not exist');
// make array of all files within this folder
const files = fs.readdirSync(`../../commands/${args[0]})
for (const file of files) {
const command = require(`../../commands/${args[0]}/${file}`) // require the file
// now you can do whatever you want with it!
console.log(command.name, command.desription)
};
Related
the message.guild.me.displayColor , which is used to set the color of the embed as the bot's highest role's color, does not work in the files in the commands folder. I have tried using:
let color = message.guild.me.displayColor
But that doesnt seem to work, however message.guild.me.displayColor works only in the index(main) file. Maybe it's the way I included the files? if so, you can review how I included those files
const commandFiles = readdirSync(join(__dirname, "commands")).filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(join(__dirname, "commands", `${file}`));
client.commands.set(command.name, command);
}
I would appreciate it if someone helps me out
While your way of reading the files looks a little off to me, I believe that it's not the issue here. Note: If your commands are not executed, try to replace it with this. You can easily check if your commands are working or not with a simple console.log("works").
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
};
Now to your actual question. Your way of setting the color doesn't work because displayColor returns the color in base 10. To use the highes role color in an embed you need to use displayHexColor as embeds cannot use base 10 colors.
let color = message.guild.me.displayHexColor;
I have a number of files in a folder in React. Each of them must be self-initialized. For this, I need to import them. I wouldn’t want to import each file individually. I need to get a list of all the files. But we do not have access to FS on the client. I tried this https://github.com/diegohaz/list-react-files solution, but it does not work (it looks like it somehow uses fs, and gives an error). Can I solve my problem in a straightforward way? Can this be done using the web-pack? Any ideas guys?
Yes, we don't have fs on the client so we need to each file manually.
but there is an easy way of doing it.
Make a registry file where you put the path of file from registry.js relative
{
"file1": "/folder1/sda.png",
"file2": "/folder2/asd.png"
}
Now you don't need to import each file manually
import registry.json
import registry from registry.json
for x in registry {
try {
require(`path to registry/${registry[x]}`)
} catch (e) {
console.log(e)
}
I'm having a hard time translating from Node.js to Appengine #google-cloud/storage.
To verify if a folder is up-to-date I go through some simple steps:
check if folder exist. If not, return false, if yes ->
check the files if they have the right name
In regular javascript, goes like this and works without problems:
if (!fs.existsSync(full_path)) {
return false;
}
else {
// else verify if all requiered files exist
let check = true;
let files = fs.readdirSync(full_path);
allExpectedFiles.forEach((f) => {
if (pfs.pfs.getFileName('pictures') !== f && files.indexOf(f) === -1) {
// console.log(c.cyan, 'Not found file: ' + f);
check = false;
}
});
return check;
}
Using #google-cloud/storage library... I just can't make it work.
I tried:
// if folder does not exist:
const dir = bucket.file(full_path);
let doesExist = await dir.exists();
console.info('For:', name, ' does folder exist?:',full_path, doesExist[0]);
if (!doesExist[0]) {
// folder does not exist so it's not uptodate
return false;
}
I got false even for thous who do exist.
Note 1: If I check with a file (adding the file name instead of ending in "/"), it works. But I need to check the folder.
Also, I tried to get the files from the folder (forcing true for folders by checking for file) and I can't get them either.
let files = await bucket.getFiles({prefix: full_path, delimiter:'.json'});
console.log(c.magenta,'Here are the files:');
console.log(files);
I got nothing. I played with prefix and delimiter but I just can't get them to work.
Note 2: I did read: How subdirectories works, but... obviously I can't get it.
Any suggestions? I'm aware that this should be a very simple task, I just can't make it work.
Later edit:
I manage to get the files but only as "all/the/long/path/filename.json". I can live with it, I'll extract the file name but it seems something is wrong, it can't be that difficult. Here is my code:
let files = await bucket.getFiles({
prefix : full_path
});
files = files[0];
files.forEach((f)=>{
console.log(c.magenta, 'Fisierele cele multe:', f.name);
});
There really are no directories in the Cloud Storage. They're just emulated based on the file paths.
So just skip the steps for checking if the destination directory exists and creating it and just go directly to checking the files in the "directory", building their file paths based on the source directory that you want to check.
In my project I have a table of projects. For each project there is a column for downloading pdf file. Now I want to be able to download all files and to create a single .rar file. There is a code for downloading a single file:
routes.js
app.get('/api/download/archive/:filename', function(req,res){
res.download("public/uploads/"+req.params.filename, req.params.filename);
})
archive.js
$scope.downloadPdf = function(obj){
$http.get('api/download/archive/'+obj.Documentation)
.success(function(data){
window.open('api/download/archive/'+obj.Documentation)
});
}
Unfortunately, RAR is a closed-source software. So the only way to create an archive is to install the command-line utility called rar and then use rar a command in a child process to compress the files.
To install rar on Mac I had to run brew install homebrew/cask/rar. You can find the installation instructions for other platforms here.
After you install it you can make use of child_process like this:
const { exec } = require('child_process');
const { promisify } = require('util');
const fs = require('fs');
const path = require('path');
// Promisify `unlink` and `exec` functions as by default they accept callbacks
const unlinkAsync = promisify(fs.unlink);
const execAsync = promisify(exec);
(async () => {
// Generating a different name each time to avoid any possible collisions
const archiveFileName = `temp-archive-${(new Date()).getTime()}.rar`;
// The files that are going to be compressed.
const filePattern = `*.jpg`;
// Using a `rar` utility in a separate process
await execAsync(`rar a ${archiveFileName} ${filePattern}`);
// If no error thrown the archive has been created
console.log('Archive has been successfully created');
// Now we can allow downloading it
// Delete the archive when it's not needed anymore
// await unlinkAsync(path.join(__dirname, archiveFileName));
console.log('Deleted an archive');
})();
In order to run the example please put some .jpg files into the project directory.
PS: If you choose a different archive format (like .zip) you would be able to make use of something like archiver for example. That might allow you to create a zip stream and pipe it to response directly. So you would not need to create any files on a disk.
But that's a matter of a different question.
Try WinrarJs.
The project lets you Create a RAR file, Read a RAR file and Extract a RAR archive.
Here's the sample from GitHub:
/* Create a RAR file */
var winrar = new Winrar('/path/to/file/test.txt');
// add more files
winrar.addFile('/path/to/file/test2.txt');
// add multiple files
winrar.addFile(['/path/to/file/test3.txt', '/path/to/file/test4.txt']);
// set output file
winrar.setOutput('/path/to/output/output.rar');
// set options
winrar.setConfig({
password: 'testPassword',
comment: 'rar comment',
volumes: '10', // split volumes in Mega Byte
deleteAfter: false, // delete file after rar process completed
level: 0 // compression level 0 - 5
});
// archiving file
winrar.rar().then((result) => {
console.log(result);
}).catch((err) => {
console.log(err);
}
Unfortunately Nodejs dosn't native support Rar compression/decompression, i frustated with this too so i created a module called "super-winrar" making super easy deal with rar files in nodejs :)
check it out: https://github.com/KiyotakaAyanokojiDev/super-winrar
Exemple creating rar file "pdfs.rar" and appending all pdf files into:
const Rar = require('super-winrar');
const rar = new Rar('pdfs.rar');
rar.on('error', error => console.log(error.message));
rar.append({files: ['pdf1.pdf', 'pdf2.pdf', 'pdf3.pdf']}, async (err) => {
if (err) return console.log(err.message);
console.log('pdf1, pdf2 and pdf3 got successfully put into rar file!');
rar.close();
});
I have sucessfully managed to make a file upload system which basically is copying files to a specific folder and save in the database its location. Now i need help with the download part. Imagine my file location is: Files/1306242602661_file1.exe, and in my view i have this:
<g:link controller="fileManager" action="downloadFile">
Download</g:link><br>
I need help with the downloadFile controller. Could you please give me a hint about how to do this, considering my filename is a string:
String fileName = "Files/1306242602661_file1.exe"
Within your controller create an download action with following content:
def file = new File("path/to/file")
if (file.exists()) {
response.setContentType("application/octet-stream")
response.setHeader("Content-disposition", "filename=${file.name}")
response.outputStream << file.bytes
return
}
// else for err message
You can render a file. see http://grails.org/doc/2.4.x/ref/Controllers/render.html
render file: new File ("path/to/file.pdf"), fileName: 'myPdfFile.pdf'