FS create file code example
Example 1: writefile in node js
const fs = require('fs');
let lyrics = 'But still I\'m having memories of high speeds when the cops crashed\n' +
'As I laugh, pushin the gas while my Glocks blast\n' +
'We was young and we was dumb but we had heart';
fs.writeFile('2pac.txt', lyrics, (err) => {
if (err) throw err;
console.log('Lyric saved!');
});
Example 2: fs.writefile
const fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
fs.writeFileSync('/tmp/test-sync', 'Hey there!');
Example 3: read file in nodejs using fs
let myFile = "./myText.txt";
const fs = require("fs");
app.all('/test', async (req, res) => {
try {
const readData = fs.readFileSync(myFile, 'utf8');
if (readData) {
res.send(readData)
}
} catch (error) {
res.send("something is wrong", error)
}
})
Example 4: fs writefile node
const fs = require('fs')
const content = 'Some content!'
fs.writeFile('/Users/joe/test.txt', content, err => {
if (err) {
console.error(err)
return
}
})
Example 5: fs create or edit file
const fs = require('fs');
fs.appendFile(‘<fileName>’,<content>,callbackFunction)