Read a file in Node.js





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







120















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?










share|improve this question




















  • 5





    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











  • 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











  • You should close this question, or supply your edit as an answer and accept it.

    – ChrisCM
    Aug 23 '13 at 13:20


















120















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?










share|improve this question




















  • 5





    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











  • 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











  • You should close this question, or supply your edit as an answer and accept it.

    – ChrisCM
    Aug 23 '13 at 13:20














120












120








120


23






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?










share|improve this question
















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?







node.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 30 '15 at 13:41









ndequeker

4,13064578




4,13064578










asked Aug 22 '13 at 16:43









Eugene KostrikovEugene Kostrikov

2,87851724




2,87851724








  • 5





    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











  • 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











  • You should close this question, or supply your edit as an answer and accept it.

    – ChrisCM
    Aug 23 '13 at 13:20














  • 5





    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











  • 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











  • You should close this question, or supply your edit as an answer and accept it.

    – ChrisCM
    Aug 23 '13 at 13:20








5




5





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





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













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





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





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













You should close this question, or supply your edit as an answer and accept it.

– ChrisCM
Aug 23 '13 at 13:20





You should close this question, or supply your edit as an answer and accept it.

– ChrisCM
Aug 23 '13 at 13:20












6 Answers
6






active

oldest

votes


















164














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.






share|improve this answer





















  • 8





    Also see readFileSync to avoid the callback.

    – Aram Kocharyan
    Jun 10 '14 at 11:59






  • 8





    @AramKocharyan Never use *Sync functions in async code. This will lock entire app until the file is read. *Sync functions are designed to be used on app start up, e.g. in modules system.

    – Eugene Kostrikov
    Jun 10 '14 at 14:10






  • 3





    Yeah in my case it was a grunt task.

    – Aram Kocharyan
    Jun 13 '14 at 0:08






  • 2





    There is a typo error in your code sample, your path.join is useless, use , instead of +

    – Yves M.
    Jul 25 '14 at 15:28













  • this code doesn't seem to be working for me, i still get the same error

    – aiden87
    Mar 13 '16 at 10:44



















30














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' });





share|improve this answer





















  • 2





    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 6 '15 at 4:39






  • 2





    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 8 '15 at 13:56



















15














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());





share|improve this answer



















  • 1





    instead of process.cwd() i think you can use __dirname variable

    – Ishikawa Yoshi
    Nov 10 '16 at 8:08



















2














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);
}
});





share|improve this answer































    2














    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());





    share|improve this answer

































      2














      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. Feel free to down vote me if you think its THAT unhelpful. 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);





      share|improve this answer
























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f18386361%2fread-a-file-in-node-js%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        164














        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.






        share|improve this answer





















        • 8





          Also see readFileSync to avoid the callback.

          – Aram Kocharyan
          Jun 10 '14 at 11:59






        • 8





          @AramKocharyan Never use *Sync functions in async code. This will lock entire app until the file is read. *Sync functions are designed to be used on app start up, e.g. in modules system.

          – Eugene Kostrikov
          Jun 10 '14 at 14:10






        • 3





          Yeah in my case it was a grunt task.

          – Aram Kocharyan
          Jun 13 '14 at 0:08






        • 2





          There is a typo error in your code sample, your path.join is useless, use , instead of +

          – Yves M.
          Jul 25 '14 at 15:28













        • this code doesn't seem to be working for me, i still get the same error

          – aiden87
          Mar 13 '16 at 10:44
















        164














        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.






        share|improve this answer





















        • 8





          Also see readFileSync to avoid the callback.

          – Aram Kocharyan
          Jun 10 '14 at 11:59






        • 8





          @AramKocharyan Never use *Sync functions in async code. This will lock entire app until the file is read. *Sync functions are designed to be used on app start up, e.g. in modules system.

          – Eugene Kostrikov
          Jun 10 '14 at 14:10






        • 3





          Yeah in my case it was a grunt task.

          – Aram Kocharyan
          Jun 13 '14 at 0:08






        • 2





          There is a typo error in your code sample, your path.join is useless, use , instead of +

          – Yves M.
          Jul 25 '14 at 15:28













        • this code doesn't seem to be working for me, i still get the same error

          – aiden87
          Mar 13 '16 at 10:44














        164












        164








        164







        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.






        share|improve this answer















        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited May 6 '17 at 7:40









        Mehdi Dehghani

        4,38842739




        4,38842739










        answered Nov 1 '13 at 7:13









        Eugene KostrikovEugene Kostrikov

        2,87851724




        2,87851724








        • 8





          Also see readFileSync to avoid the callback.

          – Aram Kocharyan
          Jun 10 '14 at 11:59






        • 8





          @AramKocharyan Never use *Sync functions in async code. This will lock entire app until the file is read. *Sync functions are designed to be used on app start up, e.g. in modules system.

          – Eugene Kostrikov
          Jun 10 '14 at 14:10






        • 3





          Yeah in my case it was a grunt task.

          – Aram Kocharyan
          Jun 13 '14 at 0:08






        • 2





          There is a typo error in your code sample, your path.join is useless, use , instead of +

          – Yves M.
          Jul 25 '14 at 15:28













        • this code doesn't seem to be working for me, i still get the same error

          – aiden87
          Mar 13 '16 at 10:44














        • 8





          Also see readFileSync to avoid the callback.

          – Aram Kocharyan
          Jun 10 '14 at 11:59






        • 8





          @AramKocharyan Never use *Sync functions in async code. This will lock entire app until the file is read. *Sync functions are designed to be used on app start up, e.g. in modules system.

          – Eugene Kostrikov
          Jun 10 '14 at 14:10






        • 3





          Yeah in my case it was a grunt task.

          – Aram Kocharyan
          Jun 13 '14 at 0:08






        • 2





          There is a typo error in your code sample, your path.join is useless, use , instead of +

          – Yves M.
          Jul 25 '14 at 15:28













        • this code doesn't seem to be working for me, i still get the same error

          – aiden87
          Mar 13 '16 at 10:44








        8




        8





        Also see readFileSync to avoid the callback.

        – Aram Kocharyan
        Jun 10 '14 at 11:59





        Also see readFileSync to avoid the callback.

        – Aram Kocharyan
        Jun 10 '14 at 11:59




        8




        8





        @AramKocharyan Never use *Sync functions in async code. This will lock entire app until the file is read. *Sync functions are designed to be used on app start up, e.g. in modules system.

        – Eugene Kostrikov
        Jun 10 '14 at 14:10





        @AramKocharyan Never use *Sync functions in async code. This will lock entire app until the file is read. *Sync functions are designed to be used on app start up, e.g. in modules system.

        – Eugene Kostrikov
        Jun 10 '14 at 14:10




        3




        3





        Yeah in my case it was a grunt task.

        – Aram Kocharyan
        Jun 13 '14 at 0:08





        Yeah in my case it was a grunt task.

        – Aram Kocharyan
        Jun 13 '14 at 0:08




        2




        2





        There is a typo error in your code sample, your path.join is useless, use , instead of +

        – Yves M.
        Jul 25 '14 at 15:28







        There is a typo error in your code sample, your path.join is useless, use , instead of +

        – Yves M.
        Jul 25 '14 at 15:28















        this code doesn't seem to be working for me, i still get the same error

        – aiden87
        Mar 13 '16 at 10:44





        this code doesn't seem to be working for me, i still get the same error

        – aiden87
        Mar 13 '16 at 10:44













        30














        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' });





        share|improve this answer





















        • 2





          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 6 '15 at 4:39






        • 2





          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 8 '15 at 13:56
















        30














        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' });





        share|improve this answer





















        • 2





          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 6 '15 at 4:39






        • 2





          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 8 '15 at 13:56














        30












        30








        30







        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' });





        share|improve this answer















        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' });






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 26 '15 at 4:16

























        answered Apr 26 '15 at 4:10









        Michael ColeMichael Cole

        9,59734356




        9,59734356








        • 2





          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 6 '15 at 4:39






        • 2





          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 8 '15 at 13:56














        • 2





          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 6 '15 at 4:39






        • 2





          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 8 '15 at 13:56








        2




        2





        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 6 '15 at 4:39





        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 6 '15 at 4:39




        2




        2





        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 8 '15 at 13:56





        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 8 '15 at 13:56











        15














        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());





        share|improve this answer



















        • 1





          instead of process.cwd() i think you can use __dirname variable

          – Ishikawa Yoshi
          Nov 10 '16 at 8:08
















        15














        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());





        share|improve this answer



















        • 1





          instead of process.cwd() i think you can use __dirname variable

          – Ishikawa Yoshi
          Nov 10 '16 at 8:08














        15












        15








        15







        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());





        share|improve this answer













        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());






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Oct 23 '16 at 7:21









        Masoud SiahkaliMasoud Siahkali

        2,4721411




        2,4721411








        • 1





          instead of process.cwd() i think you can use __dirname variable

          – Ishikawa Yoshi
          Nov 10 '16 at 8:08














        • 1





          instead of process.cwd() i think you can use __dirname variable

          – Ishikawa Yoshi
          Nov 10 '16 at 8:08








        1




        1





        instead of process.cwd() i think you can use __dirname variable

        – Ishikawa Yoshi
        Nov 10 '16 at 8:08





        instead of process.cwd() i think you can use __dirname variable

        – Ishikawa Yoshi
        Nov 10 '16 at 8:08











        2














        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);
        }
        });





        share|improve this answer




























          2














          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);
          }
          });





          share|improve this answer


























            2












            2








            2







            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);
            }
            });





            share|improve this answer













            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);
            }
            });






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 22 '13 at 11:27









            Nikunj K.Nikunj K.

            5,16842843




            5,16842843























                2














                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());





                share|improve this answer






























                  2














                  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());





                  share|improve this answer




























                    2












                    2








                    2







                    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());





                    share|improve this answer















                    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());






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Sep 23 '16 at 7:46









                    ekad

                    12.2k123742




                    12.2k123742










                    answered Sep 23 '16 at 7:26









                    Gajender SinghGajender Singh

                    38336




                    38336























                        2














                        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. Feel free to down vote me if you think its THAT unhelpful. 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);





                        share|improve this answer




























                          2














                          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. Feel free to down vote me if you think its THAT unhelpful. 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);





                          share|improve this answer


























                            2












                            2








                            2







                            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. Feel free to down vote me if you think its THAT unhelpful. 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);





                            share|improve this answer













                            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. Feel free to down vote me if you think its THAT unhelpful. 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);






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 16 '18 at 15:07









                            SovietFrontierSovietFrontier

                            433320




                            433320






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f18386361%2fread-a-file-in-node-js%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Bressuire

                                Vorschmack

                                Quarantine