node load string from file
To load a string from a file in Node.js, you can follow these steps:
- First, you need to require the built-in
fs
module by adding the following line at the beginning of your code:
const fs = require('fs');
- Next, you can use the
fs.readFileSync()
method to read the contents of the file synchronously. This method takes two parameters: the path to the file and the encoding type. For example, to read a file named "example.txt" with utf-8 encoding, you can use:
const data = fs.readFileSync('example.txt', 'utf-8');
The
readFileSync()
method returns the contents of the file as a string, which you can then assign to a variable. In the example above, the file contents will be stored in thedata
variable.Finally, you can use the
data
variable to access and manipulate the contents of the file as needed in your program.
That's it! These steps will allow you to load a string from a file in Node.js.