简体   繁体   中英

How do I write image to a specific directory with fs module in nodejs?

This is my current code:

await createCollage(pfparray, collageWidth).then((imageBuffer) => {
        pfpcollage = new MessageAttachment(imageBuffer, 'collage.png');
        fs.writeFile(`./images/${params.msg.author.id}.png`, imageBuffer, () => console.log('image downloaded'));
        }).catch(e => params.msg.channel.send({embed: {title: "Could not generate collage",description: e + " | error!"}})); 
             }

So when run, its supposed to save the image file in directory "images" with the author's id as name. However it console logs but does not actually save anything in the directory. This happens when I try saving to any specific directory. When i just try to save "${params.msg.author.id}.png" without any directory it saves it in the same directory correctly. What could be the issue?

As @h-sifat showed me, it seems the path was not being resolved. I imported the path module (Typescript [TS1259] hit an error here), I had to do

import * as path from 'path'

After, I updated my code to this:

fs.writeFile(path.resolve(__dirname,`./images/${params.msg.author.id}.png`), imageBuffer, () => console.log('image downloaded'));

This seemed to do the trick!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM