To read a file in JavaScript, you can make use of the built-in module fs
in Node.js. Here's a simple example that reads a file synchronously:
index.tsx146 chars9 lines
This code imports the fs
module and uses the readFileSync()
method to read the contents of a file called file.txt
. The second argument, 'utf8'
, specifies the character encoding of the file. In this case, it's assumed to be a text file.
If the file doesn't exist, or there's an error reading it, an error will be thrown and caught by the try...catch
block.
Alternatively, you can use the readFile()
method to read a file asynchronously:
index.tsx154 chars10 lines
This code uses the readFile()
method, which takes a callback function as its third argument. The callback function is called when the file has been read, and passed two arguments: an error (if any), and the file contents.
By default, readFile()
reads a file asynchronously, which means it won't block the rest of your program while the file is being read.
gistlibby LogSnag