2017-09-06 94 views
0

我在node.js中编写代码,我想从文件中读取数据,然后将其导出到web api。问题是,当我使用let时,出现代码错误。Node.js读取文件时出错

的错误似乎是在我的功能“render_html我views.js文件:

"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() 
} 

我也有问题, “在router.js文件功能setHeaders”:

"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!') 
}; 

有人知道问题可能是什么?

谢谢。

+0

什么包含在render_html()函数中的文件变量???文件来自哪里并设置为文件变量?当你使用fs.readFile()函数时,你需要给出一个带有文件名的文件的路径。可能在这里没有任何文件变量 –

回答

0

关于您的问题“render_html”函数我认为问题是你错过了文件的编码,因为fs doc说如果你不设置编码,结果将是一个缓冲区。您可以使用简单的修复:

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

(假设你正在使用UTF8编码为)

而且我觉得你的问题在“router.js”文件,你应该使用“writeHead”,而不是“writeHeader “您可以在http文档中查看它。

我希望它解决了您的问题,问候。