To read the contents of a .txt file in JavaScript, you can make use of the File System module, which provides functionality for working with files. Here's an example of how you can read a .txt file and print its contents:
index.tsx155 chars11 lines
In the code above, we use the readFile
method from the fs
module to read the contents of the file. The first argument is the name or path of the file you want to read (file.txt
in this case). The second argument specifies the file encoding, which is set to UTF-8 in this example. The third argument is a callback function that will be called once the file is read.
Inside the callback, we check if an error occurred. If there's an error, we log it to the console. If there's no error, we print the data to the console.
Make sure to replace file.txt
with the actual path or name of your .txt file.
Note that this code snippet assumes you are running the code in a Node.js environment, as it uses the require
function to import the fs
module. If you're working in a browser environment, you will need to use other methods, such as fetch
or the FileReader API, to read files.
Remember to handle errors and edge cases according to your specific use case.
gistlibby LogSnag