fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
I have a question regarding the use of the function fs.writeFile() in Node, and the fact that it prints strings into a textfile.
At the moment, I have a piece of code that prints the following into console. Instead of the console, I would like to modify the code a bit so it would print into a textfile.
var options = {
host: 'www.google.com',
path: '/'
};
http.get(options, function(response) {
console.log("Status Code: " + response.statusCode);
for(var item in response.headers) {
console.log(item + ": " + response.headers[item]);
}
I would like to replace console.log with fs.writeFile, however, the Hello Node part of the input in fs.writeFile() is a string. Thus, I am stuck on this part.
The documentation for fs.writeFile() for Node.js is here: http://nodejs.org/api/fs.html
As explained in the documentation, this is how the fs.writeFile function works fs.writeFile(filename, data, [encoding], [callback]). My question is in regards to the data input.
I am fairly new to Node.js, therefore I would like to get some feedback on this, and hopefully work the solution out myself with some pointers.
EDIT 1: Do I use String() which then turns my function into a string? I don't think this is right, but it could be a possibility.
This is the code that solved it:
http.get(options, function(res) {
fs.appendFile('log.txt', "Status Code: " + res.statusCode + "\n");
for(var item in res.headers) {
fs.appendFile('log.txt', item + ": " + res.headers[item] + "\n");
}
}).on('error', function(e) {
console.log("Error: " + e.message);
});
I used fs.appendFile