首页 > 解决方案 > console.log 不是 nodejs fs.readfile 中的函数

问题描述

我正在平静地学习nodejs。我正在学习 fs.readFile。所以为了练习,我做了一个简单的代码。

var list;
fs.readFile('list.txt', 'utf8', function(err, data){
list=data;
});

但是当我得到列表的值时,它是“未定义的”。

所以,我试着像这样控制数据的价值

var list;
fs.readFile('list.txt', 'utf8', function(err, data){
list=data;
console.log(data);
});

问题开始了。
我收到错误,TypeError:console.log 不是函数。

所以,我检查了很多这样这样的问题......

但我找不到我的问题的答案。

为什么会发生此错误,我该如何阻止这种情况发生?

完整的代码是

var http = require('http');
var fs = require('fs');
var url = require('url');
  var printconsole="";
function console(data){
  return "<script>console.log(\""+data+"\");</script>";
}
  var app = http.createServer(function(request,response){
  var template;
    var _url = request.url;
    var queryData = url.parse(_url, true).query;
    var title = queryData.id;
    var main;
    var list;
    fs.readFile('list.txt', 'utf8', function(err, data){
        console.log("data");
        list=data;
    });
    fs.readFile(`${queryData.id}.txt`, 'utf8', function(err, data){ 
        main=data;
    });
    if(_url == '/'){
      title = 'Web';
      main = `world wide web`;
    }
    if(_url == '/favicon.ico'){
      return response.writeHead(404);
    }
    response.writeHead(200);
    template = `
    <!doctype html>
    <html>
    <head>
      <style>
        body{
          width:-webkit-fill-availble;
          height:-webkit-fill-availble;
        }
        header{
          width:100%;
          height:10%;
          border-bottom:1px solid #111111;
        }
        aside{
          width:10%;
          height:560px;
          border-right:1px solid #111111;
          float:left;
        }
        article{
          width:85%;
          height:85%;
        }
      </style>
      <meta charset="utf-8">
    </head>
    <body>
          <header><h1>${title}</h1></header>
          <aside>${list}</aside>
           <article>${main}</article>
        </body>
    </html>
    `;
    response.end(template);
});

app.listen(3000);

标签: javascripthtmlnode.jsconsolefs

解决方案


function console(data){
  return "<script>console.log(\""+data+"\");</script>";
}

你用你自己的函数覆盖console了,它没有log属性。


推荐阅读