Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Writing files in Node.js

I've been attempting to figure out how to write to a file when utilizing Node.js, however with no achievement. How might I do that?
by

3 Answers

akshay1995
There are a lot of details in the File System API. The most common way is:

const fs = require('fs');

fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});

// Or
fs.writeFileSync('/tmp/test-sync', 'Hey there!');
niharikasaitana
const fs = require('fs');

fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
here we are importing fs module by using rquire to write and read fle data
MounikaDasa
var path = 'public/uploads/file.txt',
buffer = new Buffer("some content\n");

fs.open(path, 'w', function(err, fd) {
if (err) {
throw 'error opening 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('file written');
})
});
});

Login / Signup to Answer the Question.