1

trying to read a file using 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); ^ ReferenceError: data is not defined

Asanka
  • 483
  • 2
  • 8
  • 21
  • Have you tried using "./details.txt" as the path? – mcgraphix Apr 17 '16 at 14:07
  • @mcgraphix — Why should that make a difference? – Quentin Apr 17 '16 at 14:09
  • 1
    I can't think of any reason why `err` would be false but `data` undefined. – Quentin Apr 17 '16 at 14:10
  • ./ refers to the working directory. Juat trying to ensure it is looking in the right place. – mcgraphix Apr 17 '16 at 14:15
  • yes. still giving the same error. – Asanka Apr 17 '16 at 14:21
  • i changed the code to this var fs = require('fs'); fs.readFile("./details.txt",'',function(err,data) { if(!err) { return console.log(err); } response.writeHead(200, {"Content-Type":"text/html"}); response.write(data); }); now im getting a error in console "null" which is in the if statement – Asanka Apr 17 '16 at 14:36

3 Answers3

1

File order

Above img shows my File order. Note: I'm using IntelliJ IDEA. You will have to find the file "details.txt" in your system.

//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();
  }
});
Michael Seltene
  • 543
  • 1
  • 5
  • 17
0

Try using the full path to 'details.txt' (i.e. '/etc/hosts'). And, send it to console.log just to confirm it works.

Gary Stafford
  • 331
  • 3
  • 10
0
   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)