0

I am trying to parse excel file data in the server and it is working fine but the problem is that it is saving file which we upload in the local disk in upload folder and then it is reading data.Here is the code which is working fine but when uploading large xlsx file is the issue because it will require extra memory and create same as another file in local disk.

server.route({
    method: 'post',
    path: `${(options.apiBase || '/xlsx/')}get`,
    config: {
        payload: {
            output: 'stream',
            parse: true,
            allow: 'multipart/form-data'
        }
    },
    handler: function (req, reply) {
        try {
            const data = req.payload;
            if (data.file) {
                let name = data.file.hapi.filename;
                console.log("FIlename: " + name);

                let path = __dirname + "/uploads/" + name;
                let file = fs.createWriteStream(path);

                data.file.pipe(file);
                data.file.on('end', function (err) {

                    if (typeof require !== 'undefined')
                        XLSX = require('xlsx');

                    const workbook = XLSX.readFile(path);
                    console.log("row======>>>>");
                    const sheet_name_list = workbook.SheetNames;
                    const content =
                        XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
                    console.log(content);

                    var ret = {
                        filename: data.file.hapi.filename,
                        headers: data.file.hapi.headers
                    }
                    reply(JSON.stringify(content));
                })
            } catch (err) {
                console.log('Err----------------------' + err);
                // error handling
                reply(Boom.badRequest(err.message, err));
            }
        }
});

next();
jkris
  • 5,851
  • 1
  • 22
  • 30
willy
  • 3
  • 4
  • the hapijs docs mention that a temporary file gets created on every upload. You can choose to delete this file after doing the processing – Yashveer Rana Sep 10 '17 at 21:32

1 Answers1

0

You need to set config.payload.parse to false. This will return the raw stream. But realize that if you're uploading multipart/form-data, you will need to parse it yourself.

config: {
    payload: {
        output: 'stream',
        parse: false,
        allow: 'multipart/form-data'
    }
}

This is handled by the subtext module. See https://github.com/hapijs/subtext/blob/0bf83af78e364518577913db1bbc9c27bc739d7a/lib/index.js#L67

Jeff Kilbride
  • 2,614
  • 1
  • 20
  • 21