Caine Nielsen
Caine Nielsen

Reputation: 327

Cannot read property 'toString' of undefined node.js filesystem

I have this script here, upon loading the page, it should first load a header html boilerplate, some dynamic paragraphs, and end the request with a footer html boiler plate. Both Boilerplates come from external files.

After testing, I am receiving:

TypeError: Cannot read property 'toString' of undefined at ReadFileContext.callback (/user_code/index.js:20:23) at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:367:13)

My understanding was that I needed .toString() to ensure that what was loaded from the external files were buffered as strings.

exports.request = functions.https.onRequest((req, res) => {

        fs.readFile('/public/templates/header-template.html', function(_err, data) {
            res.write(data.toString());
            console.log('Header Loaded');
        });

        res.writeHead(200, {'Content-Type': 'text/html'});
        var q = url.parse(req.url, true).query;
        var txt = '<p>Thanks <b>' + q.firstname + ' ' + q.lastname + '</b>. An email has been sent to <b>' + q.email + '</b> with details about your request.';
        res.write(txt);

        fs.readFile('/public/templates/footer-template.html', function(_err, data) {
            res.end(data.toString());
            console.log('Footer Loaded');
        });

    });

Any idea what I am doing wrong?

Upvotes: 1

Views: 9719

Answers (1)

Alejandro Zuleta
Alejandro Zuleta

Reputation: 180

You should pass the encoding to toString() to convert from a Buffer.

data.toString('utf8');

Additionally, it seems your variable data is not defined, so perfhaps your file doesn't exists. Capture the error and see what's wrong:

if(_err){
   console.error(_err);
}

Upvotes: 1

Related Questions