1

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.

2
  • 1
    if it's streaming, redirect it to a local file codewinds.com/blog/2013-08-19-nodejs-writable-streams.html Commented 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. Commented Mar 22, 2017 at 16:50

2 Answers 2

3

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!');
});
Sign up to request clarification or add additional context in comments.

1 Comment

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!
1

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();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.