I am coding a Discord bot that can write to a local text file on glitch.com.
When I use the ready event handler my program is able to write to the file just fine:
client.on('ready', () => {
fs.appendFile('./log.txt', 'Hello\n', (err) => {
if(err) throw err;
});
});
//Writes to file
However, when I try to write to the same file using the message event handler, nothing happens:
client.on('message', (message) => {
fs.appendFile('./log.txt', 'Hello\n', (err) => {
if(err) throw err;
});
});
//Does not write to file
Do I need to change permissions on this file? Or change it from a local file? Any help would be greatly appreciated.
I think something like this might work, I don't have time to test it but it's using the writeFile() method as opposed to the appendFile() method
client.on('message', (message) => {
fs.writeFile('./log.txt', message, (err) => {
if(err) throw err;
});
});
Assuming you already have your local text file you wouldn't need to make a new one. So you may as well use writeFile(), only thing I can see going wrong with this is it may refresh the file every message, but you could probably fix that with a message collector that updates the file every say 100 messages.
Using appendFileSync instead of appendFile should fix your issue, as appendFileSync is more reliable and has less of a chance to create errors. Good luck!
Related
how can I catch an error in NodeJS or create own error code and send it to the frontend to inform the user?
In the following code I am looking into the database result if there were any data deleted and try to send an error code. How can I send the error code to my react frontend? Maybe using response.json("Not deleted any user"). Tried it already out.
How can I prevent my server from crashing? If the sql is not correcting because there was no id send to delete it is crashing.
Thanks for the answers for this two cases.
db.getConnection((err, connection) => {
if (err) throw err;
connection.query(
"DELETE FROM users where users_id = ?",
[2],
(err, rows) => {
connection.release();
if (rows.affectedRows == 0) {
throw err;
}
if (err) throw err;
if (!err) {
res.redirect("/");
} else {
console.log(err);
}
console.log("Daten gelöscht", rows.affectedRows);
}
);
});
You should use a try, catch block. If you want to throw a custom exception, you can do something like
throw new NotFoundException("Record with the given id Not Found...!!!"):
I use it in nestjs I am not fully sure that this will work for you but you can try :)
I am using Formidable with Express in nodeJS in an attempt to have a simple single file upload scheme. I have confirmed that a file is actually sent over from the client-side, but where it seems to run into troubles is on the server-side.
index.js
app.post('/', (req, res) => {
const form = formidale();
form.on('file', (filename, file) => {
fs.rename(file.path, `./data/nodes.csv`, err => {
if (err) {
console.log(`There was an error in downloading a CSV file: ${err}`);
return null;
}
else {
console.log("CSV file has been uploaded correctly.");
}
});
});
form.on('error', err => {
console.log(`There was an error in downloading a CSV file: ${err}`);
return null;
});
form.on('end', () => {
console.log(fs.readFileSync('./data/nodes.csv')); // test to see if file exists
const nodes = assignMetrics();
console.log(nodes);
return nodes;
});
form.parse(req);
});
}
The main trouble I seem to find is that the form.on('end', ...) event does not seem to wait till the file has finished uploading to fire. I have confirmed this by trying to read the file in the event, but by that point it doesn't exist? The documentation though appears to suggest it is only meant to fire "after all files have been flushed [from the APIs pipe it infers]".
There appears to be no other events available that might wait till the file has been uploaded to be called? I also don't want to start throwing in layers of promises and such unless it is the only option, as each new layer of promises I find is a chance for unintended effects to happen.
I have been trying to make a simple program to create and read files with Electron.
So far I have tried a lot and it seems the callback function I provide with the dialog.showOpenDialog is not being called.
dialog.showOpenDialog( (filePaths) => {
console.log('this callback is called');
console.log(filePaths);
});
//Directly read a test file
fs.readFile('readtest.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log(data);
});
This is the code inside my read button handler.
The dialog opens and I choose a file and it simply does nothing.
However the same file which I selected is read by the fs.readFile and displayed in the console.
It seems the callback is not getting called after I choose the file.
It returns a promise, so you can chain it with .then:
dialog.showOpenDialog(null, options).then((filePaths) => {
console.log('this callback is called');
console.log(filePaths);
});
I have a file readData.txt has the values "10,20,30,40,50,........"like this I have the numbers.
Now I want to write the sum of those values in to the other file called sumfile.txt. I'm using fs.readFile and fs.writeFile functions which are asynchronous.
I have tried using Promises, It worked. But I'm curious that can we do it without using Promises. I'm trying to achieve that without Promises.
If anybody know any other ways I'll be thankful.
You can use the callback parameter of fs.readFile:
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
You can use the callback parameter of fs.writeFile:
const data = new Uint8Array(Buffer.from('Hello Node.js'));
fs.writeFile('message.txt', data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
EDIT
You can do this synchronously as well, using fs.readFileSync
fs.readFileSync('<directory>');
and fs.writeFileSync
But it is better to keep things async. It is difficult at first, but all your struggles will be rewarded.
so I was trying to get the metainfo from a youtube URL using ytdl in Node.js
here's the code I'm currently trying to get working :
ytdl.getInfo('https://www.youtube.com/watch?v=YQHsXMglC9A',{downloadURL: true},
function(err, info) {
if (err) throw err;
console.log(info.title);
}
);
So, this works fine and I get the title of the song. Now i'm trying to actually GET the info as in stocking it in a var for me to use later. And I can't get to manage it, I tried to return something from the callback methode or catching whatever getInfo() is giving but it keep saying it's 'undefined'.
If any of you have some ideas i'll be glad to try these.
Thanks, Lucas
maybe do something like this
ytdl.getInfo('https://www.youtube.com/watch?v=YQHsXMglC9A',{downloadURL: true},
function(err, info) {
if (err) throw err;
var songTitle = info.title //you can store it here
console.log(songTitle);
}
);
When downloading a video/audio using ytdl-core use a event handler instead!
The information will going to be fetched first, then audio/video is going to be downloaded.
ytdl(youtube_url)
.on('info', (info) => {
console.log(info.title); // the video title
});