FS (File System Module) in Node.js
First import 'fs' (file system) module using:
const fs = require('fs')
###Read a file Syntax:
const file = fs.readFileSync("Relative_Directory_Path/file.js",{encoding: 'utf-8'})
//just write the encoding part even if you don't know what does it mean
Test 1:
const fs = require('fs')
const file = fs.readFileSync("./lib.js") #Reading without specifying encoding
console.log(file)
Output:
PS F:\Projects\NodeJs\Test> node playground.js
<Buffer 6d 6f 64 75 6c 65 2e 65 78 70 6f 72 74 73 20 3d 20 28 29 20 3d 3e 20 7b 0d 0a 20 20 20 20 76 61 6c 75 65 3a 31 2c 0d 0a 20 20 20 20 75 73 65 72 49 64 ... 68 more bytes>
Test 2:
const fs = require('fs')
const file = fs.readFileSync("./lib.js",{encoding: 'utf-8'}) #reading with encoding method
console.log(file)
Output:
PS F:\Projects\NodeJs\Test> node playground.js
module.exports = () => {
value:1,
userIds: [1,2,3],
action() {
console.log('action')
}
}
In Test1 we read the file successfully but the result which we got was encoded while in Test2 we mentioned the encoding method due to which we are able to read file content as a String.
How to write in a file
First import 'fs' (file system) module using:
const fs = require('fs')
Syntax:
fs.writeFileSync('Relative_Directory_Path/file.js','Conentent you want to write in the file.js')
For Example:
fs.writeFileSync('./lib.js','var me="hello"')
Output: lib.js
var me="hello"