I am using node and I have some code that I run that puts the data from an API call out in a certain JSON format I need for dynamo. It is about 23000 records or so a day and I am attempting to save them to my hard drive. Can someone please let me know how to save the output of a variable to a file? I have seen other pages on here but most of them seem to cover an html element with onclick or something along those lines. I appreciate any help.
-
1if it's streaming, redirect it to a local file codewinds.com/blog/2013-08-19-nodejs-writable-streams.htmllonewarrior556– lonewarrior5562017-03-22 16:41:45 +00:00Commented Mar 22, 2017 at 16:41
-
yes, it streams. When I console.log(JSON.stringify(client, null,'\t')); it brings back all of the information. I just need a way to save that to a file. I will check out your link above.Mike– Mike2017-03-22 16:50:25 +00:00Commented Mar 22, 2017 at 16:50
Add a comment
|
2 Answers
In node to write in a new file or replace old
var fs = require('fs'); // reqire fileSystem node module
fs.writeFile("pathToFile", "Content", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
Or append to existing file
fs.appendFile("pathToFile", "Content", function (err) {
if (err) throw err;
console.log('Saved!');
});
1 Comment
Mike
I actually just happened upon and tried this exact method right before i saw that you posted it, but it was exactly what i needed! So thanks man. I didn't know about the append and have a feeling it will come in handy for what I need it for. Thanks!
One of the most common ways to log something from JavaScript is to use AJAX to post the value of the JavaScript variable. You can use any server-side script, including Node's FileSystem API to save a log of the variable to a specific file.
Example:
function saveVariable(variable) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("Saved");
}
};
xhttp.open("POST", "save?var=" + variable, true);
xhttp.send();
}