3

I'm having trouble understanding how to access a local file in a Node.js Expresss Webapp.

I want to use the excel-parser package to read a file I have placed in /public/assets/ this should be read on load of the index page.

So I have started by creating an ExpressJS app, and creating the following in my index.js:

exports.index = function(req, res){
  var excelParser = require('excel-parser')

  res.render('index', { title: 'Excel test' });

  excelParser.worksheets({
    inFile: '/assets/test_data.xlsx'
    }, function(err, worksheets){
      if(err) console.error(err);

      console.log('[INFO] Worksheet output: ');
      console.log(worksheets);
    });
};

In ny console though I receive the error 'File not found', and 'worksheets' is undefined.

I have also tried with the following paths:

  • /public/assets...
  • __dirname + '/public/assets/...'
  • __dirname + '/assets/...'

All offer the same error.

Blaise
  • 132
  • 1
  • 1
  • 9
  • Checked file permissions? – PP. Jul 10 '13 at 16:11
  • according to docs `__dirname` isn't actually a global but rather local to each module. So it depends where your index file is. You could `require('path')` and then `path.join(__dirname, 'public/assets')` thats when index file is in same directory as public – Ivar Jul 10 '13 at 16:14

1 Answers1

4

You need to get file relatively to you app root directory. As right now '/assest' will try to get it from root of your drive.

You can get root directory of main JS file early in module:

var path = require('path');
var root = path.dirname(require.main.filename);

And then use it:

inFile: root + '/public/assets/test_data.xlsx'
moka
  • 22,846
  • 4
  • 51
  • 67
  • Thanks that led me to the solution. I also used [fs.exists](http://nodejs.org/api/fs.html#fs_fs_exists_path_callback) to help me track down that I was calling a file that actually existed. – Blaise Jul 11 '13 at 08:09