Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[nodejs] read and write a file

https://nodejs.dev/learn/reading-files-with-nodejs

https://nodejs.dev/learn/writing-files-with-nodejs

        const fs = require("fs")

        try {
            // read from local folder
            const localPDF = fs.readFileSync('PDFs/myFile.pdf')

            //write back to local folder
            fs.writeFileSync('PDFs/writtenBack.pdf', localPDF )

        } catch (err) {
            console.error(err)
        }

Converting to Base64

        try {
            // read from local folder
            const localPDF = fs.readFileSync('PDFs/myFile.pdf')
            const localBase64 = localPDF.toString('base64')

            //write back to local folder
            fs.writeFileSync(`PDFs/writtenBack.pdf`, localBase64, {encoding: 'base64'})

        } catch (err) {
            console.error(err)
        }

Reading and writing using streams with pipe

        //read and write local file
        const reader = fs.createReadStream("PDFs/myFile.pdf")
        const writer = fs.createWriteStream('PDFs/writtenBack.pdf');
        reader.pipe(writer)

Leave a Reply

Your email address will not be published. Required fields are marked *