Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

javascript - Create File object without saving

I'm trying to look for a way to create a .txt File object without saving it to disk in Node.js. In browser I'd do something like

new File(['file_contents'], 'file_name.txt', {type: 'text/plain'})

The end aim is to create a .txt file object temporarily for my Discord Bot to send as a message attachment.

From the discord.js documentation, I presume I'm supposed to create a Buffer or Stream object representing the file.

I'm already using require('node-fetch') library to read attachments in messages, if that has any relevancy (but can't see anything in their docs on this either).

question from:https://stackoverflow.com/questions/65913168/create-file-object-without-saving

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In order to write a text file in JS you should use the fs library, included in Node.js.

Here is an example of writing to a file:

fs = require('fs');

let content = "Hello world!";

fs.writeFile('file.txt', content, function (err) {
    if (err) return console.log(err);
    // Code here will execute if successfully written
});

Then in order to send a local file to Discord you can use .send with an object containing a files property in it, like this:

channel.send({
    files: [{
        attachment: 'entire/path/to/file.txt',
        name: 'file.txt'
    }]
}).then(() => {
    // Delete file
    fs.unlink('file.txt');
});

You can see more about .send() here and you can find more about the fs module here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...