node write to a file code example
Example 1: node js write file
const fs = require('fs');
let path = 'ghetto_gospel.txt';
let buffer = new Buffer('Those who wish to follow me\nI welcome with my hands\nAnd the red sun sinks at last');
fs.open(path, 'w', function(err, fd) {
if (err) {
throw 'could not open file: ' + err;
}
fs.write(fd, buffer, 0, buffer.length, null, function(err) {
if (err) throw 'error writing file: ' + err;
fs.close(fd, function() {
console.log('wrote the file successfully');
});
});
});
Example 2: how to write to a file with javascript without nodejs
function convertToJSON() {
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
var email = document.getElementById('email').value;
var jsonObject = {
"FirstName": firstname,
"LastName": lastname,
"email": email
}
document.getElementById('output').value = JSON.stringify(jsonObject)
}
function saveToFile() {
convertToJSON();
var jsonObjectAsString = document.getElementById('output').value;
var blob = new Blob([jsonObjectAsString], {
type: 'octet/stream'
});
console.log(blob);
var anchor = document.createElement('a')
anchor.download = "user.json";
anchor.href = window.URL.createObjectURL(blob);
anchor.innerHTML = "download"
anchor.click();
console.log(anchor);
document.getElementById('output').append(anchor)
}