257

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?

ndequeker
  • 7,932
  • 7
  • 61
  • 93
Eugene Kostrikov
  • 6,799
  • 6
  • 23
  • 25
  • 9
    Chances are the file isn't where you/the code thinks it is. If the file is in the same directory as the script, try: `path.join(__dirname, 'start.html')` – dc5 Aug 22 '13 at 16:51
  • 1
    Can you console.log("__dirname: " + __dirname); right before you output err? That will tell what directory is local for your executable at that moment. There are things you can do to change your location and maybe you are hitting that, maybe the code isn't operating at the __dirname where you think it is. – Brian Aug 22 '13 at 17:17
  • The file needs to be in the same directory that you run the node process from. So if the file is in dir/node/index.html and so is your app.js file but you do: node /dir/node/app.js Then you receive an error. dc5's solution should do the trick. – Evan Shortiss Aug 22 '13 at 17:22
  • use `path.join(__dirname, '/filename.html')` and take reference from https://stackoverflow.com/a/56110874/4701635 – Paresh Barad May 13 '19 at 11:36
  • This was also helpful for me for NodeJS reading a local file: https://stackoverflow.com/a/67579901/470749 – Ryan Oct 21 '21 at 18:32

8 Answers8

312

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

var fs = require('fs'),
    path = require('path'),    
    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.

Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
Eugene Kostrikov
  • 6,799
  • 6
  • 23
  • 25
65

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' });
Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Michael Cole
  • 15,473
  • 7
  • 79
  • 96
  • 7
    Don't use any `*Sync` methods when programming for the web. These are only appropriate for grunt/gulp tasks, console apps, etc. They pause the entire process while reading. The OP's code references `response` so it's clearly a web app where `readFileSync` is not appropriate. – Samuel Neff Jun 06 '15 at 04:39
  • 3
    Regardless of whether or not there are other use cases (and loading files to a cache at start-up is definitely not one of them), the OP's post is definitely not a case where you want to use `readFileSync`--he's in the middle of processing a web request. This answer was totally inappropriate to the question at hand. – Samuel Neff Jun 08 '15 at 13:56
  • @SamuelNeff, 7 years later hope you are well. I disagree with this as premature optimization. Node is single-threaded event loop, so technically, EVERY function locks the server. Some functions for longer than others, so you pay your money and take your chances on milliseconds. It's not anything we need to scold new users about. It's definitely low-hanging fruit for performance optimization, and a perfectly good pattern for all skill levels. – Michael Cole Jan 07 '23 at 22:02
  • "EVERY function locks the server" is only the case for when the function code is running. A synchronous IO call will lock the server for the entire IO call whereas an async IO call will lock only when the function starts and when the IO comes back but not in between (these days with async/await but back then with callbacks). Except in local scripts and maybe at app startup, you never want to do that. This has nothing to do with premature optimization, it's plain and simple wrong. The fact that this answer got 65 upvotes is very disappointing. – Samuel Neff Mar 17 '23 at 18:45
41

1).For ASync :

var fs = require('fs');
fs.readFile(process.cwd()+"\\text.txt", function(err,data)
            {
                if(err)
                    console.log(err)
                else
                    console.log(data.toString());
            });

2).For Sync :

var fs = require('fs');
var path = process.cwd();
var buffer = fs.readFileSync(path + "\\text.txt");
console.log(buffer.toString());
Masoud Siahkali
  • 5,100
  • 1
  • 29
  • 18
35

simple synchronous way with node:

let fs = require('fs')

let filename = "your-file.something"

let content = fs.readFileSync(process.cwd() + "/" + filename).toString()

console.log(content)
localhostdotdev
  • 1,795
  • 16
  • 21
21

Run this code, it will fetch data from file and display in console

function fileread(filename)
{            
   var contents= fs.readFileSync(filename);
   return contents;
}        
var fs =require("fs");  // file system        
var data= fileread("abc.txt");
//module.exports.say =say;
//data.say();
console.log(data.toString());
Gajender Singh
  • 1,285
  • 14
  • 13
6

To read the html file from server using http module. This is one way to read file from server. If you want to get it on console just remove http module declaration.

var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
  fs.readFile('HTMLPage1.html', function(err, data) {
    if (!err) {
      res.writeHead(200, {
        'Content-Type': 'text/html'
      });
      res.write(data);
      res.end();
    } else {
      console.log('error');
    }
  });
});
server.listen(8000, function(req, res) {
  console.log('server listening to localhost 8000');
});
<html>

<body>
  <h1>My Header</h1>
  <p>My paragraph.</p>
</body>

</html>
Alexpandiyan Chokkan
  • 1,025
  • 1
  • 10
  • 30
Aaditya
  • 61
  • 1
  • 1
  • The above code is to read the html file on server .you can read the html file on server , by creating server using "http" module. This is the way to response file on server. You can also remove "http" module to get it on console – Aaditya Sep 15 '19 at 08:45
  • 1
    Hey there, you might want to include your comment in the answer by clicking the edit button. – Glenn Watson Sep 15 '19 at 08:54
4

If you want to know how to read a file, within a directory, and do something with it, here you go. This also shows you how to run a command through the power shell. This is in TypeScript! I had trouble with this, so I hope this helps someone one day. What this did for me was webpack all of my .ts files in each of my directories within a certain folder to get ready for deployment. Hope you can put it to use!

import * as fs from 'fs';
let path = require('path');
let pathDir = '/path/to/myFolder';
const execSync = require('child_process').execSync;

let readInsideSrc = (error: any, files: any, fromPath: any) => {
    if (error) {
        console.error('Could not list the directory.', error);
        process.exit(1);
    }
    
    files.forEach((file: any, index: any) => {
        if (file.endsWith('.ts')) {
            //set the path and read the webpack.config.js file as text, replace path
            let config = fs.readFileSync('myFile.js', 'utf8');
            let fileName = file.replace('.ts', '');
            let replacedConfig = config.replace(/__placeholder/g, fileName);

            //write the changes to the file
            fs.writeFileSync('myFile.js', replacedConfig);

            //run the commands wanted
            const output = execSync('npm run scriptName', { encoding: 'utf-8' });
            console.log('OUTPUT:\n', output);

            //rewrite the original file back
            fs.writeFileSync('myFile.js', config);
        }
    });
};

// loop through all files in 'path'
let passToTest = (error: any, files: any) => {
    if (error) {
        console.error('Could not list the directory.', error);
        process.exit(1);
    }

    files.forEach(function (file: any, index: any) {
        let fromPath = path.join(pathDir, file);
        fs.stat(fromPath, function (error2: any, stat: any) {
            if (error2) {
                console.error('Error stating file.', error2);
                return;
            }

            if (stat.isDirectory()) {
                fs.readdir(fromPath, (error3: any, files1: any) => {
                    readInsideSrc(error3, files1, fromPath);
                });
            } else if (stat.isFile()) {
                //do nothing yet
            }

        });
    });
};

//run the bootstrap
fs.readdir(pathDir, passToTest);
miken32
  • 42,008
  • 16
  • 111
  • 154
SovietFrontier
  • 2,047
  • 1
  • 15
  • 33
-1
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);
  }
});
Nikunj K.
  • 8,779
  • 4
  • 43
  • 53
  • 2
    This answer adds a lot of unnecessary noise. There's a few variables that are not used, meaningless comments, and everything is exported. – devklick Mar 01 '22 at 10:11