nodejs load file

Paths in Node are resolved relatively to the current working directory. Prefix your path with __dirname to resolve the path to the location of your Node script.

var fs = require('fs');
fs.readFile( __dirname + '/test.txt', function (err, data) {
  if (err) {
    throw err; 
  }
  console.log(data.toString());
});

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('../test.txt');

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

You should use __dirname to get the directory name the file is located instead of the current working directory:

fs.readFile(__dirname + "/test.txt", ...);