nodejs read and write file
nodejsTo read and write files in Node.js, you can use the fs module. This module provides a set of functions to read, write, and manipulate files in a Node.js application.
Here are some examples of how you can use the fs module to read and write files:
Reading a file:
const fs = require('fs');
fs.readFile('/path/to/file', (error, data) => {
if (error) {
console.error(error);
return;
}
console.log(data);
});
The readFile()
function reads the contents of a file and returns it as a buffer. You can also pass an encoding as the second argument, in which case the file contents will be returned as a string.
Writing a file:
const fs = require('fs');
const content = 'Hello World';
fs.writeFile('/path/to/file', content, (error) => {
if (error) {
console.error(error);
return;
}
console.log('File written successfully');
});
The writeFile()
function writes the specified content to a file. If the file does not exist, it will be created. If the file already exists, it will be overwritten.
Other Article on Tag nodejs
- - axios Request path contains unescaped characters
- - CryptoJS.HmacSHA256 Cannot read properties of undefined (reading 'sigBytes')
- - encrypt by java and decrypt by node
- - fetch function mode sors, no-cors, same-origin
- - How to set value for NODE_TLS_REJECT_UNAUTHORIZED
- - it error Request path contains unescaped characters
- - java vs nodejs
- - nodejs add redis
- - nodejs call api get request
- - nodejs connect mysql database