简体   繁体   中英

Node.js error in reading file

I am writing code in node.js where i want to read from a file and then export it to a web api. The problem is that I get an error on the code when i am using let.

The error appears to be in my function "render_html my views.js file:

"use strict";
const fs = require('fs');
const model = require('./model');


exports.car = (request, response, params) => {
    if (Object.keys(params).length === 0) {
        render_JSON(response, model.cars())
    }else{
        render_JSON(response, model.cars(parseInt(params.number)))
    }
};

function render_html(response, file) {
    fs.readFile(file, (err, data) => {
        if (err) {
            console.error(err)
        } else {
            response.write(data);
            response.end();
        }
    });
}

function render_JSON(response, object) {
    const responseJSON = JSON.stringify(object);
    response.write(responseJSON);
    response.end()
}

I also have problem in "function setHeaders" in router.js file:

"use strict";
const views = require('./views');
const url = require('url');


const routes = [
    {
        url: ['/api/cars'],
        view: views.car,
        methods: ['GET'],
        headers: {'Content-Type': 'application/json; charset=UTF-8'} // application/json as per RFC4627
    }];

function setHeaders(response, headers = {'Content-Type': 'text/plain'}, code = 200) {
    response.writeHeader(code, headers);
}

// Filters trailing slash in the url
// for example allowing /api/cars and /api/cars/ to be treated equally by removing trailing slash in the second case
function filterURL(requestURL) {
    if (requestURL.pathname.endsWith('/')) {
        requestURL.pathname = requestURL.pathname.replace(/\/$/, '');
    }
}

exports.route = (request, response) => {
    for (let r of routes) {
        const requestURL = url.parse(request.url, true);
        // url matched and correct method
        //if requestURL.pathname
        filterURL(requestURL);
        if (r.url.includes(requestURL.pathname) && r.methods.includes(request.method)) {
            if (r.headers) {
                setHeaders(response, r.headers);
            } else {
                setHeaders(response)
            }

            r.view(request, response, requestURL.query);
            return;
        }// if unsupported HTTP method
        else if (r.url.includes(requestURL.pathname) && !r.methods.includes(request.method)) {
            setHeaders(response, undefined, 405);
            response.end();
            return;
        }
    }
    // if route not found respond with 404
    setHeaders(response, undefined, 404);
    response.end('404 Not Found!')
};

Somebody knows what the problem could be?

thanks.

about your problem in "render_html" function I think the problem is you are missing the encoding of the file, as fs doc says if you dont set a encoding the result will be a buffer. You can easy fix it using:

fs.readFile(file, 'utf8', callback)

(Assuming that you are using utf8 as encoding)

And I think your problem in "router.js" file is you should use "writeHead" instead "writeHeader" you can check it in http doc.

I hope it solves your issue, greetings.

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