Api to write a file using nodejs and graphql

 Reading a file and  http request using axios
const country_list = require('../../Public/countrylist_deivercharge');
const token_check = require('../../Global/tokenvalidator');
const fs = require('fs');
let axios = require('axios');
updateDeliveryCashe: ({ EMAIL, TOKEN }) => {

        return token_check.token_verify(EMAIL, TOKEN)
            .then(async (data) => {
                if (data == "TOKEN_INVALID" || data == "TOKEN_EXPIRED" || data == "RECORD_NOT_FOUND")
                    return { summary: { status: "SUCCESS", reason: data } }

                else if (data == "TOKEN_VALID") {
                    
                    let nodeJsCode = '';
                    nodeJsCode = `const country_list =  ${JSON.stringify(country_list, "utf-8", 4)};
                    module.exports = country_list;`;
                    fs.writeFileSync('graphql/Public/countrylist_deivercharge.js', nodeJsCode, (err) => {
                        if (err) {
                            //  console.error(err)
                            return err;
                        }

                    })
                    
                    let options = {
                        host: 'localhost',
                        port: 3000,

                        url: WEBSTORE_UPLOAD + 'delivery/server ',
                        method: 'POST',
                        headers: {

                            "Content-Length": Buffer.byteLength(nodeJsCode)
                        },
                        data: nodeJsCode
                    };
                    
                    return axios(options)
                        .then(function (response) {

                            return response.data;
                        })
                        .catch(function (error) {
                            console.log(error);
                            return { summary: { status: "SUCCESS", reason: "RECORD_NOT_FOUND" } }
                        });

                }
            })
            .catch(function (error) {
                console.log(error);
                return { summary: { status: "SUCCESS", reason: "RECORD_NOT_FOUND" } }
            });

    }
Api for writing  a File 
router.post('/upload/delivery/server', (req, res) => {

    //write file in node file
    let writeDeliveryCharge = fs.createWriteStream('./graphql/Public/countrylist_deivercharge.js');
    req.pipe(writeDeliveryCharge)
    req.on('end', function () {

        let adminDashboard = {
            "summary": {
                status: "SUCCESS", reason: "RECORD_UPDATED"
            }
        }
        res.send(adminDashboard);

    });


    writeDeliveryCharge.on('error', function (err) {
        console.log(err);
    });

});

Leave a comment

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