Blaise
Blaise

Reputation: 132

File not found in Node.js

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:

All offer the same error.

Upvotes: 3

Views: 16807

Answers (1)

moka
moka

Reputation: 23053

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'

Upvotes: 4

Related Questions