using forEach inside a string - javascript

Im trying to use fs to make a Command-Handler for ESM(ECMAScript) because you can't use fs in ESM i have 2 js enviornments, one with ESM and one with Node.js the Node env is only there so it reads all file names of a folder and uses the names to import and export them inside a file that the other env uses. I allready have it so the names get stored inside a const in the node env but when i try to write them with fs it gives me an error, and when i try to log the string it says undefined
const fs = require("fs")
const commands = []
try {
fs.unlinkSync("./scripts/modules/commands.js")
console.log('\x1b[32m File Deleted Succesfully \x1b[0m')
} catch (e) {
console.error(e)
}
try {
fs.openSync("./scripts/modules/commands.js", 'w')
console.log('\x1b[32m Created File Successfully')
} catch (e) {
console.error(e)
}
try {
const cCommands = fs.readdirSync("./scripts/modules/commands/").filter(file => file.endsWith('.js'));
for (const file of cCommands) {
const name = file.replace(".js", "")
commands.push(name)
}
console.log('\x1b[32m Pushed all Files Successfully \x1b[0m\n')
} catch (e) {
console.error(e)
}
// This outputs => 'ping' as a string
console.log(`${commands}`)
// This outputs => undefinedexport const commands = {undefined}; but should output => import {ping} from './commands/ping'; export const commands = {ping:ping};
console.log(`${commands.forEach(command => `import {${command}} from './commands/${command}';`)}export const commands = {${commands.forEach(command => `${command}:${command},`)}};`)
try {
const cmdString = `${commands.forEach(command => `import {${command}} from './commands/${command}';`)}export const commands = {${commands.forEach(command => `${command}:${command},`)}};`
const jsonString = JSON.stringify(cmdString);
fs.writeFile("./scripts/modules/commands.js", jsonString)
console.log(jsonString)
console.log('\x1b[32m Send all Commands Successfully \x1b[0m')
} catch (e) {
console.error(e)
}
Edit: Changed all .forEach() functions to .map() now this error accures => TypeError [ERR_INVALID_ARG_TYPE]: The "cb" argument must be of type function. Received undefined

To fix this error just use fs.writeFileSync instead of fs.writeFile

Related

slashCommands.push(slashCommand.data.toJSON()); | TypeError: Cannot read properties of undefined (reading 'toJSON')

I started the bot as usual, in the handler or other file from the slash command I didn't change anything.
anyone know how to group? I need it now, and I can't find anything on the internet.
I started doing the bot at 1 p.m., now when I am writing this it is 10:13 p.m. and the problem appeared only around 9:30 p.m.
I don't know what to write next but they keep telling me so have a nice day / night: D
const fs = require('fs')
const { REST } = require('#discordjs/rest')
const { Routes } = require('discord-api-types/v9')
const token = process.env['token']; //get the token in .env
const guild = process.env['guild']; //get the guild ID in .env
const application_id = process.env['application_id']; //get the application ID in .env
module.exports = (client) => {
const slashCommands = []; //make a variable
fs.readdirSync('./slashCommands/').forEach(dir => {
const slashCommandFiles = fs.readdirSync(`./slashCommands/${dir}/`).filter(file => file.endsWith('.js'));
for (const file of slashCommandFiles) {
const slashCommand =require(`../slashCommands/${dir}/${file}`);
slashCommands.push(slashCommand.data.toJSON());
if(slashCommand.data.name) { //if the slash command file has a name
client.slashCommands.set(slashCommand.data.name, slashCommand)
console.log(file, '- Success') //check if the file load and log in console
} else {
console.log(file, '- Error') //if the file doesn't have command name, log it error in console
}
}
});
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try{
console.log('Start registering application slash commands...')
await rest.put(
guild
? Routes.applicationGuildCommands(application_id, guild) //registered the slash command in guild
: Routes.applicationCommands(application_id), //registered the slash command globally
{
body: slashCommands,
}
);
console.log('Successfully registered application slash commands.')
} catch (err) {
console.log(err);
}
})();
};
One of the files located in this directory is missing the data object: require(../slashCommands/${dir}/${file});
A fix that will stop the error, but will also render the file useless would be skipping over the file that is missing data or data.toJSON()
for (const file of slashCommandFiles) {
const slashCommand = require(`../slashCommands/${dir}/${file}`)
if (!slashCommand.data || !slashCommand.data.toJSON()) continue
// Carry on with code after here
}

Sveltekit & Fleek (IPFS) import syntax problem?

I have managed to use fleek to update IPFS via straight javascript. I am now trying to add this functionality to a clean install of a svelteKit app. I think I am having trouble with the syntax around imports, but am not sure what I am doing wrong. When I click the button on the index.svelte I get the following error
Uncaught ReferenceError: require is not defined
uploadIPFS upload.js:3
listen index.mjs:412..........(I truncated the error here)
A few thoughts
I am wondering if it could be working in javascript because it is being called in node (running on the server) but running on the client in svelte?
More Details
The index.svelte file looks like this
<script>
import {uploadIPFS} from '../IPFS/upload'
</script>
<button on:click={uploadIPFS}>
upload to ipfs
</button>
the upload.js file looks like this
export const uploadIPFS = () => {
const fleek = require('#fleekhq/fleek-storage-js');
const apiKey = 'cZsQh9XV5+6Nd1+Bou4OuA==';
const apiSecret = '';
const data = 'pauls test load';
const testFunctionUpload = async (data) => {
const date = new Date();
const timestamp = date.getTime();
const input = {
apiKey,
apiSecret,
key: `file-${timestamp}`,
data
};
try {
const result = await fleek.upload(input);
console.log(result);
} catch (e) {
console.log('error', e);
}
};
testFunctionUpload(data);
};
I have also tried using the other import syntax and when I do I get the following error
500
global is not defined....
import with the other syntax is
import fleekStorage from '#fleekhq/fleek-storage-js';
function uploadIPFS() {
console.log('fleekStorage',fleekStorage)
};
export default uploadIPFS;
*I erased the api secret in the code above. In future I will store these in a .env file.
Even more details (if you need them)
The file below will update IPFS and runs via the command
npm run upload
That file is below. For my version that I used in svelte I simplified the file by removing all the file management and just loading a variable instead of a file (as in the example below)
const fs = require('fs');
const path = require('path');
const fleek = require('#fleekhq/fleek-storage-js');
require('dotenv').config()
const apiKey = process.env.FLEEK_API_KEY;
const apiSecret = process.env.FLEEK_API_SECRET;
const testFunctionUpload = async (data) => {
const date = new Date();
const timestamp = date.getTime();
const input = {
apiKey,
apiSecret,
key: `file-${timestamp}`,
data,
};
try {
const result = await fleek.upload(input);
console.log(result);
} catch(e) {
console.log('error', e);
}
}
// File management not used a my svelte version to keep it simple
const filePath = path.join(__dirname, 'README.md');
fs.readFile(filePath, (err, data) => {
if(!err) {
testFunctionUpload(data);
}
})

Discord.js Error: EISDIR: illegal operation on a directory, read

When i try executing this code i get an error. "Error: EISDIR: illegal operation on a directory, read".
Line 18 : Column 19
const { Client, Intents, Collection } = require('discord.js')
const config = require('./config.json')
const fs = require('fs')
const bot = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES ] })
bot.commands = new Collection()
var cmdFiles = fs.readFileSync('./cmd').filter(f => f.endsWith(".js"))
for(const f in cmdFiles) {
const cmd = require(`./commands/${f}`)
bot.commands.set(cmd.help.name, cmd)
}
bot.once("ready", () => {
console.log('Bot is ready!')
})
bot.on("messageCreate", async message => {
if(message.author.bot) return;
var prefix = config.prefix
if(!message.content.startsWith(prefix)) return;
var array = message.content.split(" ");
var command = array[0];
const data = bot.commands.get(command.slice(prefix.length))
if(!data) return;
var args = array.slice(1)
try {
await data.run(bot, message, args)
} catch(e) {
await message.channel.send(e)
await console.log(e)
}
})
bot.login(config.token)
Yes all config things are defined.
I've tried searching for this error but got nothing that i need.
What i want to do is load every file from the directory 'cmd' in a array list and run a command if it is called.
Change this:
var cmdFiles = fs.readFileSync('./cmd').filter(f => f.endsWith(".js"));
to this:
var cmdFiles = fs.readdirSync('./cmd').filter(f => f.endsWith(".js"));
As your question states, ./cmd is a directory and you can't list the files in a directory with fs.readFileSync(). You would use fs.readdirSync() to do that.
fs.readFileSync() tries to open the directory as a file and read its contents. Since it's not a file, you get the EISDIR error.

How To Unit Test Entry Point Node.js File With Jest

I have an entry point in my app that is executed via npm start. I'd like to run some tests on this script with Jest, but cannot figure out how I should do it. The script automatically runs, so if I import it into a Jest file, I can't call it individually in my test blocks like:
const entryPoint = require('./entry-point')
test('something', () => {
entryPoint()
})
The code will already execute before it reaches any of the test blocks.
The code for the entry point is here:
const fs = require("fs");
const summarizeData = require("./summarize-data");
try {
const fileName = process.argv[2];
if (!fileName) {
throw Error("Please enter a file name. ex: npm start <filename>");
}
if (!fs.existsSync(`${fileName}.json`)) {
throw Error(`The file ${fileName}.json could not be found.`);
}
const jsonParsed = JSON.parse(fs.readFileSync(`${fileName}.json`, "utf8"));
const data = summarizeData(jsonParsed);
console.log(data);
} catch (error) {
throw Error(error);
}
I think it will be enough to unit test summarizeData function.
Something like this (using shouldJS for assertions):
const should = require('should');
const fileName = 'testData';
test('it summarize data properly', () => {
const jsonParsed = JSON.parse(fs.readFileSync(`${fileName}.json`, "utf8"));
const dataSummarized = summarizeData(jsonParsed);
dataSummarazied.something.should.be.equal(1); // TODO - add other assertions to cover all result
})

How to check if each file in a path is accessible for reading or not

I am trying to read the contents of a specific path. for that purpose, i used the following code:
code1:
const contentsOfPersonalFolder = fs.readdirSync(rootPathToPersonal);
but i know in advance that i do not have access permission to read some of the contents that will be returned from the previous line of code.
To check whether or not I have access permission to read some files, i would use the following code
code2:
try {
fs.accessSync(path, fs.constants.R_OK);
logger.info('The directory: ', path, 'can be read');
} catch (err) {
logger.error('The directory: ', path, 'can not be read due inaccessibility');
}
The problem now is, the code in code1 will return an array of all available files in the specified path. and if one of the these files is not
accessible due read right protection, then it will throw and the program will throw.
what i want to achieve is to iterate through all the available files in the specified path in code1, and then check each item using the code in code2 and
if the file is accessible for reading i would like to do some logic, and if it is not accessible for reading i would do something else.
please let me know how to achieve that.
you could use fs.access to check the users permissions
https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback
const testFolder = './tests/';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
console.log(file);
fs.access(file, fs.constants.R_OK, (err) => {
if (err) {
console.error("file is not readable");
return;
}
// do your reading operations
});
});
})
const fs = require('fs');
const isAvailableToRead = file => {
try {
fs.accessSync(file, fs.constants.R_OK);
return true;
} catch (err) {
return false;
}
}
const readDirectory = path => {
const files = fs.readdirSync(path);
files.forEach(file => {
if(isAvailableToRead(file)) {
console.log(`Do some logic ${file}`);
}
});
}
readDirectory(__dirname);

Categories