To avoid having to change every emoji from every file whenever I switch an emoji, I decided to place an emojis.json and call the emoji from there.
emojis.json
{
"loading": "<a:loading:847653387343626301>",
"pressf": "<:pressf:862166705911758909>"
}
Exampleping.js
const emoji = require('../emojis.json')
module.exports = {
name: 'ping',
execute(message, args) {
message.channel.send(`${emoji.loading}Pong.`)
}
}
Is this the right way? I'm open to new/better ideas.
Btw it errors: code: 'MODULE_NOT_FOUND',
Well, your approach is correct to a certain extent. Only issue is that you have imported a json file instead of js file and hence it throws an error.
Correct way of achieving this, is having a emojis.js file with your json object exported using module.exports
// emojis.js
module.exports = {
loading: "<a:loading:847653387343626301>",
pressf: "<:pressf:862166705911758909>"
};
// Exampleping.js
const emojis = require('../../emojis.js')
module.exports = {
name: 'ping',
execute(message, args) {
message.channel.send(`${emoji.loading}Pong.`)
}
}
Your code is clean except your import statement is not referring to the emojis.json file. To make it more clear, the script failed to locate the file, which means emojis.json is not located inside the same directory as exampleping.js (require('./emojis.js')).
Based on my experience with Discord bot development, I believe you placed emojis.json in your root directory while exampleping.js is placed inside a directory commonly named "commands". With that being said, all you need is to exist the command directory by adding another . to require().
const emojis = require('../emojis.js');
//instead of ./emojis.json
See HTML File Path
Related
I am working with react. I have a file to download. and its download to browser default save location(Download folder)
FileSaver.saveAs(res.data, fileTitle + "." + fileExtension);
I have found that its not possible to change with FileSaver.saveAs method. So i want to know is there a another method in react to save file to local path.
You can't save a file to a particular path using FileSaver library.
But there's a new File System API you can use to achieve that. There's a project by googlechromelabs, a simple text editor (demo), designed to experiment with and demonstrate the new File System Access APIs.
Create a new file.
To save a file, call showSaveFilePicker(), which shows the file picker in "save" mode, allowing the user to pick a new file they want to use for saving
async function getNewFileHandle() {
const options = {
types: [
{
description: 'Text Files',
accept: {
'text/plain': ['.txt'],
},
},
],
};
const handle = await window.showSaveFilePicker(options);
return handle;
}
Save changes to disk
// fileHandle is an instance of FileSystemFileHandle..
async function writeFile(fileHandle, contents) {
// Create a FileSystemWritableFileStream to write to.
const writable = await fileHandle.createWritable();
// Write the contents of the file to the stream.
await writable.write(contents);
// Close the file and write the contents to disk.
await writable.close();
}
I am trying to upload a file by using sendKeys method and adding absolute path to file but the file does not get uploaded. I think sendKeys method doesn't work very well on react pages. Can someone please help and give a workaround of this problem? Below is the code snippet:
I do not see any error but the file doesn't get uploaded.
Below is the function I am using to upload file:
importFileButton: {
get: function() {
return this.findElement(this.by.xpath("//div[#id='upload-file']//button[#aria-label='Import file Browse ']"))
}
}
attachCommaFile: {
get: function () {
browser.setFileDetector(new remote.FileDetector());
var fileToUpload = './../../files/fileimport_Pipe.txt',
absolutePath = path.resolve(__dirname, fileToUpload);
return this.importFileButton.sendKeys(absolutePath);
}
}
file uploads work with input tags
You're trying to sendKeys to a wrong element - button
Most like the tag you're looking for will have the following css [type=file]
for more detailed info see this post https://stackoverflow.com/a/66110941/9150146
Is it possible to use the client/bot constant across different files?
My index.js file has gotten pretty clogged up, so I tried splitting different functions into different files.
I already tried exporting the bot constant from index.js:
// in index.js
module.exports = {
Gbot: bot
}
// in different file
const index = require('../index.js')
const bot = index.Gbot
bot.on('message', message => {
message.channel.send("test")
})
The second file does not do anything, it does not respond with "test"
There is no errors either
Is this not possible or am I doing something wrong?
This is possible, but why do you want to do that? If you are using a Command Handler you define client or bot to use it everywhere. And if not you are running everything in index.js, the file where you defined client or bot.
Edit:
//index.js
module.exports.Gbot = bot;
//other file
const index = require("../index.js");
const bot = index.Gbot;
I'm trying to import multiple files with a certain extension in a folder:
const allEntries = require.context('../static/blog', true, '/\.md/')
but I'm getting:
Unhandled Rejection (TypeError): __webpack_require__(...).context is not a function
I'm using Nextjs and require the files in one of the pages. Something seems off here?
Edit: I don't necessarily need to do it via require I just want to be able to import/require multiple files at once without knowing the filename or how many of the files are in a folder.
You can give the following a try in webpack:
const glob = require('glob');
const allEntries = glob.sync("../static/blog/*.md");
The glob will return an array of files. The array will contain all files with .md extension in the ../static/blog/ folder. Eventough there is a package it shouldn't be required to install the package.
Try using require context npm library.
$ npm i --save require-context
In your file:
// Load globally into all modules.
require('require-context/register')
// Load locally as a function.
var requireContext = require('require-context');
function requireAll(r) { r.keys().forEach(r); }
requireAll(requireContext('../static/blog', true, /\.md$/));
From what I understand you are very close, from the error you are using webpack's require.context
const allEntries = require.context('../static/blog', true, '/\.md/')
console.log(allEntries.keys()) // all the files found in the context
allEntries.keys().forEach(allEntries) // require them all
const imageDirectory = path.join(process.cwd(), '/public/dirname');
const imageFilenames = await fs.readdir(imageDirectory)
// Store the file names in an array and use it.
webpack.require is basically using webpack, make sure what you're using is webpack in fact
I've successfully instantiated a simple AudioWorklet in React and wish to start a simple oscillator like in Google's example. In order to test run it, I am rendering a button whose onClick event calls the following:
src/App.jsx:
userGesture(){
//create a new AudioContext
this.context = new AudioContext();
//Add our Processor module to the AudioWorklet
this.context.audioWorklet.addModule('worklet/processor.js').then(() => {
//Create an oscillator and run it through the processor
let oscillator = new OscillatorNode(this.context);
let bypasser = new MyWorkletNode(this.context, 'my-worklet-processor');
//Connect to the context's destination and start
oscillator.connect(bypasser).connect(this.context.destination);
oscillator.start();
})
.catch((e => console.log(e)))
}
The problem is, on every click, addModule method is returning the following error:
DOMException: The user aborted a request.
I am running Chrome v66 on Ubuntu v16.0.4.
src/worklet/worklet-node.js:
export default class MyWorkletNode extends window.AudioWorkletNode {
constructor(context) {
super(context, 'my-worklet-processor');
}
}
src/worklet/processor.js
class MyWorkletProcessor extends AudioWorkletProcessor {
constructor() {
super();
}
process(inputs, outputs) {
let input = inputs[0];
let output = outputs[0];
for (let channel = 0; channel < output.length; ++channel) {
output[channel].set(input[channel]);
}
return true;
}
}
registerProcessor('my-worklet-processor', MyWorkletProcessor);
My code is straight JavaScript, not React, but I got the same error because the path provided to addModule was incorrect. In my case, both the script that calls addModule and the script provided as the argument to addModule reside in the same directory ("js"). In spite of that, I still had to include this directory in the path to eliminate the error:
...addModule('js/StreamTransmitter.js')...
I hope this helps. Good luck!
For anyone else getting this mysterious error, swallow your pride and check the following:
The processor doesn't have any errors.
The processor is calling external modules with proper path to the external file(s).
The external modules don't have any errors.
The promise will abort when external modules that are loaded via "import" have errors, or the paths to the modules can't be resolved (e.g. the path's to the modules are wrong and don't point to existing files).
This worked for me: serve your worklet files from public folder instead of src. The addModule(url) function points there by default, so addModule('worklets/foo.js') references file public\worklets\foo.js
Source: https://hackernoon.com/implementing-audioworklets-with-react-8a80a470474
This seems to be a bug in the Chromium module loader, it parses the worklet/processor.js file by removing whitespace, which in turn causes it to have JavaScript syntax errors everywhere, which then finally causes this generic non-explanatory error message to show up.
The solution is to serve your worklet-processors (e.g. worklet/processor.js in your case) with:
Content-Type: application/javascript
or
Content-Type: text/javascript
I also experienced this error but due to a Webpack issue.
Turns out webpack doesn't support worklets like it supports web workers (see this issue).
I would recommend using worker-url with webpack.
Install worker-url
npm i --save-dev worker-url
Update your webpack config to include the WorkerUrl plugin.
const WorkerUrlPlugin = require('worker-url/plugin');
module.exports = {
// ...
plugins: [new WorkerUrlPlugin()],
// ...
};
Use WorkerUrl like so:
import { WorkerUrl } from 'worker-url';
const workletUrl = new WorkerUrl(
new URL('./random-noise-processor', import.meta.url),
{ name: 'worklet' },
);
await context.audioWorklet.addModule(workletUrl);
The Error "DOMException: The user aborted a request." happens when the AudioWorklet.addModule() function cannot load the file from the path or URL you provided. Refer to this MDN page
The api AudioWorklet.addModule() expects a String containing the URL of a JavaScript file with the module to add.
It can be an internal URL that points to your public folder where the browser loads your static files in this case -> 'worklet/processor.js if the worklet folder is inside the public directory of your React app.
You can modify your code as below.
this.context.audioWorklet.addModule('worklet/processor.js')
In this case the audioWorklet.addModule() method expects the path to point to your public folder. It can also be an external URL for example a link to Github repository that loads the JS file.
Changing:
this.context.audioWorklet.addModule('worklet/processor.js')
with
this.context.audioWorklet.addModule('../worklet/processor.js')
worked for me.