0

How can I require the package 'fs' on the server only and on the client resolve null?

If you try to run this on the client: Module not found: Can't resolve 'fs'

(The potential duplicate question How to check whether a script is running under node.js? does not answer this problem)

const isNode =
  typeof process !== 'undefined' &&
  process.versions != null &&
  process.versions.node != null;

const fs = isNode && require('fs');
BAR
  • 15,909
  • 27
  • 97
  • 185
  • Possible duplicate of [How to check whether a script is running under node.js?](https://stackoverflow.com/questions/4224606/how-to-check-whether-a-script-is-running-under-node-js) – Alexander Lallier Jul 30 '19 at 17:39
  • Last line should be `const fs = isNode ? require('fs') : null` – badal16 Jul 30 '19 at 17:49
  • Another way to check for node environment `typeof process !== "undefined" && process.release && process.release.name === "node";` – ambianBeing Jul 30 '19 at 17:50
  • We are already checking the node env. That is not the problem here. require('fs') on the client will still fail. – BAR Jul 30 '19 at 17:52
  • Okay. Why not require condtionally inside if clause keeping fs as `let`. Unless you strictly want to keep it as `const`. – ambianBeing Jul 30 '19 at 17:58
  • @AmbianBeing That doesn't work. Even inside an 'if' require() will still be called. – BAR Jul 30 '19 at 18:02

0 Answers0