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.

4

1 回答 1

4

您需要获取相对于您的应用程序根目录的文件。现在,'/assest' 将尝试从驱动器的根目录获取它。

您可以在模块的早期获取主 JS 文件的根目录:

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

然后使用它:

inFile: root + '/public/assets/test_data.xlsx'
于 2013-07-10T16:16:17.270 回答