Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack bundle ENOENT: no such file or directory fs.readdirSync

We would like to create micro apps that run on AWS Lambda. We are investigating webpack 2 for this. However, we have legacy code that uses fs.readdirSync to get a list of file/module names to generate a module list. When executing the bundle we get an error Error: ENOENT: no such file or directory, scandir '/innerLib' because webpack does not know to execute fs.readdirSync(path.resolve(__dirname, 'innerLib')); in file lib/lib.js and resolve an array of file names during bundle time.

What approaches can we take with wepback without making major changes to the legacy code. I have included a simple example below and on github

webpack.config.js

var path = require( 'path' );
var webpack = require( 'webpack' );

module.exports = {
  context: __dirname,
  entry: ['./index.js'],
  output: {
    filename: 'bundle.js',
  },
  target: 'node',
}

index.js

const  lib = require('./lib/lib.js');

lib.getModuleList((err, modules) => console.log(modules));

lib/lib.js

const fs = require('fs');
const path = require('path');
let moduleList = [];
let list = fs.readdirSync(path.resolve(__dirname, 'innerLib'));

exports.getModuleList = getModuleList;

function getModuleList(callback) {
  return callback(null, moduleList);
}

list.forEach(filename => {
  moduleList.push({
    name: filename
  });
});

lib/innerLib/a.js

console.log('a lib loaded');

lib/innerLib/b.js

console.log('b lib loaded');
like image 936
isurfbecause Avatar asked Dec 30 '25 21:12

isurfbecause


1 Answers

Your problem is that __dirname is resolving to /. To get it to work with webpack, set:

node: {
  __dirname: true
}

in your webpack.config.js. After adding that, your bundle executes fine for me.

like image 149
christopher fujino Avatar answered Jan 01 '26 14:01

christopher fujino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!