开发者问题收集

TypeError:无法读取未定义的属性“length”。在节点js中

2019-09-17
211

TypeError: Cannot read property 'length' of undefined at /Users/junggri/Desktop/web2-nodejs/syntax/main.js:15:36 at FSReqWrap.args [as oncomplete] (fs.js:140:20)

这是我的 Node js 代码

var http = require('http');
var fs = require('fs');
var url = require('url');
var app = http.createServer(function(request,response){
var _url = request.url;
var queryData = url.parse(_url, true).query;
var pathname = url.parse(_url, true).pathname;
if(pathname === '/'){
if(queryData.id === undefined){
fs.readdir('./data', function(error, filelist){
var title = 'Welcome';
var description = 'Hello, Node.js';
var list = '<ul>';
for(var i =0; i<filelist.length; i++){
list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;}
list = list+'</ul>';
var template = `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">WEB</a></h1>
${list}
<h2>${title}</h2>
<p>${description}</p>
</body>
</html>
`;
response.writeHead(200);
response.end(template);
})
2个回答

读取目录似乎存在问题。如之前的回答中指出的,请检查回调中的错误参数。它将为您提供必要的详细信息。

Aadil Khanday
2019-09-17

您可以尝试这样的操作:

var filelist = fs.readdirSync('./data/');
Sunny Parekh
2019-09-17