javascript - console.log 不是 nodejs fs.readfile 中的函数

标签 javascript html node.js console fs

我正在安静地学习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);
});

问题现在就开始了。
我收到错误, 类型错误:console.log 不是函数。

所以,我检查了很多问题,例如 thisthis ...

但我找不到问题的答案。

为什么会发生此错误?如何阻止此错误发生?

完整代码为

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);

最佳答案

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

您使用自己的函数覆盖了 console,该函数没有 log 属性。

关于javascript - console.log 不是 nodejs fs.readfile 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53690597/

相关文章:

javascript - 使用 scrollTop() 从浏览器窗口底部检测 30%

html - 使网站规模化而不是响应式

node.js - 在Express中渲染jade时包含其他文件的内容吗?

node.js - 使用 git-tracked heroku 项目时如何安全地存储 .pem 文件?

javascript - JQuery 对话框在升级到 Bootstrap 4 时不显示内容

javascript - 将属性和值推送到嵌套数组中的特定位置

html - 用显示 :table-cell 填充可用空间

html - Internet Explorer 中的图像很大,而 firefox 和 chrome 都很好

node.js - React Native 不会在模拟器上本地获取

javascript - Angular 5,如果第一个函数有效则执行新函数