尝试使用node.js
读取文件 var fs = require('fs');
fs.readFile("details.txt",'utf8',function(err,data)
{
if(err)
{
return console.log(err);
}
response.write(data);
});
在同一目录中有一个文件alredy和一些文本。
我得到的错误是:
回复于(数据); ^ ReferenceError:未定义数据
答案 0 :(得分:1)
上面的img显示了我的文件顺序。注意:我使用的是IntelliJ IDEA。你必须找到文件" details.txt"在你的系统中。
//Instead of using hard coded path, use: the following code to get the path in Node.js
//var path = require('path');
//console.log(path.join(__dirname, '../details.txt'));
//require file system
var fs = require('fs');
//read file
fs.readFile("details.txt",'utf8',function(err,data){
//if error, log error and return
if(err) { return console.error('Error: ' + err); }
//check if there is data in the file
if(data) {
//EDITED to include line break
//write response
//response.write('<div style="color:green">' + data + '</div>');
//write response with <br>
response.write('<div style="color:green">' + data.split('\n').join('<br>') + '</div>');
//end the response
response.end();
//if no data on the file, do the following
}else{
//error variable
var error = "Error: file is empty: " + data.length + " bytes.";
//log error
// console.error(error);
//write response
response.write('<div style="color:red">' + error + '</div>');
//end response
response.end();
}
});
答案 1 :(得分:0)
尝试使用完整路径&#39; details.txt&#39; (即&#39; / etc / hosts&#39;)。并将其发送到console.log以确认它是否有效。
答案 2 :(得分:0)
var fs = require('fs');
fs.readFile("details.txt",'utf8',function(err,data)
{
if(err)
{
return console.log(err);
}
console.log(data);
});
错误是
response.write(data)