When I try to import the fs module in my own module like import * as fs from 'fs'
the following error in the browser console comes:
Uncaught TypeError: Failed to resolve module specifier "fs". Relative references must start with either "/", "./", or "../"
.
Using require
or using a relative path to the module like ./node_modules/fs
will not work, is there any other way of importing the fs module correctly?
Advertisement
Answer
You have two basic problems, both of which stem from the fact you are running this code in a browser and not in Node.js.
Passing something like 'fs'
to import
depends on Node.js style module resolution. Node.js will search the contents of the node_modules
folder for matching modules. Browsers can’t do that, they haven’t got a file system to search; they only deal in URLs.
When dealing with modules in a browser you have to pass either:
- A URL that includes an absolute path (like
/fs
orhttp://example.com/fs
) - A URL that is an explicitly relative path (like
../fs
or./fs
).
… just like the error message says.
(Typically you’ll also need to put a .js
on the end of the URL because your HTTP server is unlikely to do that for you).
You also need to use a module which will run in a browser in the first place.
fs
is a Node.js built-in module. It does things which browsers do not allow JavaScript to do (like access the file system).
If you want to use the fs
module then you can’t use it directly from the browser. Instead, write a web service in Node.js (the Express.js module is useful here) and access it from the browser using Ajax (e.g. the fetch
API). This will deal with the server’s file system, not the browser’s.
If you want to access files on the user’s computer, then you’ll need to use <input type="file">
and the FileReader
API.