Organizational Research By

Surprising Reserch Topic

read a file in node js


read a file in node js  using -'node.js'

I'm quite puzzled with reading files in Node.js.

fs.open('./start.html', 'r', function(err, fileToRead){
    if (!err){
        fs.readFile(fileToRead, {encoding: 'utf-8'}, function(err,data){
            if (!err){
            console.log('received data: ' + data);
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write(data);
            response.end();
            }else{
                console.log(err);
            }
        });
    }else{
        console.log(err);
    }
});


File start.html is in the same directory with file that tries to open and read it.

However, in the console I get:


  { [Error: ENOENT, open './start.html'] errno: 34, code: 'ENOENT', path: './start.html' }


Any ideas?
    

asked Sep 18, 2015 by sanjaypal1983
0 votes
4 views



Related Hot Questions

3 Answers

0 votes

Use path.join(__dirname, '/start.html');

var fs = require('fs');
var path = require('path');

var filePath = path.join(__dirname, 'start.html');

fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
    if (!err){
    console.log('received data: ' + data);
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.write(data);
    response.end();
    }else{
        console.log(err);
    }

});

Thanks to dc5.

answered Sep 18, 2015 by amit_cmps
0 votes
var fs = require('fs');
var path = require('path');

exports.testDir = path.dirname(__filename);
exports.fixturesDir = path.join(exports.testDir, 'fixtures');
exports.libDir = path.join(exports.testDir, '../lib');
exports.tmpDir = path.join(exports.testDir, 'tmp');
exports.PORT = +process.env.NODE_COMMON_PORT || 12346;

// Read File
fs.readFile(exports.tmpDir+'/start.html', 'utf-8', function(err, content) {
  if (err) {
    got_error = true;
  } else {
    console.log('cat returned some content: ' + content);
    console.log('this shouldn\'t happen as the file doesn\'t exist...');
    //assert.equal(true, false);
  }
});
answered Sep 18, 2015 by rajeevr642
0 votes

With Node 0.12, it's possible to do this synchronously now:

  var fs = require('fs');
  var path = require('path');

  // Buffer mydata
  var BUFFER = bufferFile('../public/mydata.png');

  function bufferFile(relPath) {
    return fs.readFileSync(path.join(__dirname, relPath)); // zzzz....
  }

fs is the file system. readFileSync() returns a Buffer, or string if you ask.

fs correctly assumes relative paths are a security issue. path is a work-around.

To load as a string, specify the encoding:

return fs.readFileSync(path,{ encoding: 'utf8' });
answered Sep 18, 2015 by jekbishnoi

...