[英]reading a file using node.js
trying to read a file using node.js尝试使用 node.js 读取文件
var fs = require('fs');
fs.readFile("details.txt",'utf8',function(err,data)
{
if(err)
{
return console.log(err);
}
response.write(data);
});
there is a file alredy with some text in the same directory.在同一目录中有一个文件已经包含一些文本。
Error im getting is :我得到的错误是:
response.write(data); response.write(data); ^ ReferenceError: data is not defined
^ 参考错误:数据未定义
Above img shows my File order.上面的 img 显示了我的文件顺序。 Note: I'm using IntelliJ IDEA.
注意:我使用的是 IntelliJ IDEA。 You will have to find the file "details.txt" in your system.
您必须在系统中找到文件“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();
}
});
Try using the full path to 'details.txt' (ie '/etc/hosts').尝试使用“details.txt”的完整路径(即“/etc/hosts”)。 And, send it to console.log just to confirm it works.
并且,将它发送到 console.log 只是为了确认它的工作原理。
var fs = require('fs');
fs.readFile("details.txt",'utf8',function(err,data)
{
if(err)
{
return console.log(err);
}
console.log(data);
});
the error is错误是
response.write(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.