javascript - 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);
解决方案
function console(data){ return "<script>console.log(\""+data+"\");</script>"; }
你用你自己的函数覆盖console
了,它没有log
属性。
推荐阅读
- django - 如何在模板中通过 for 循环显示 help_text 属性?
- codeigniter-3 - CI3 HMVC + 休息 + 角度 12
- angular - 角度材料表过滤列和日期范围
- apache-spark - 带有 spark 的 Kotlin 从 POJO 创建数据帧,其中包含 pojo 类
- postgresql - Citus 10.2 未启动 PostgreSQL 实例
- arrays - 在字节数组中向右移动字节的方法
- php - Json 无法解析
- ios - 如何在导航栏右侧添加图片和文字
- python - python中的单下划线与双下划线封装
- c++ - 向对向量添加元素会引发错误:分割违规信号