1

I want to redirect the output of node.js to txt file.I am able to get the output in console for node.js.

Please help me in this issue.

This is the snippet:

node.forEach(function(elem)
{
var toString=elem.path.toString;
console.log(toString);
}

Output looks something like this

ui.apps/src/main/content/jcr_root/components/content/smartcart/deviceselector/cq_editConfig.xml
ui.apps/src/main/content/jcr_root/components/content/smartcart/deviceselector/deviceselector.html

2 Answers 2

2

Writing a string to a file

If you are just trying to save the output from that one particular function, you can use the fs node core module

var fs = require("fs");

var output = "";
for (var i = 0; i < node.length; i++) {
    var elem = node[i];
    output += elem.path.toString() + "\n";
}

fs.writeFile("output.txt", output, function (err) {
    if (err) {
        return console.log(err);
    }
    console.log("output.txt saved");
});

Writing all output to a file

If you are trying to capture everything that is logged to a log file, you have a number of options:

  1. Use a loggin package such as winston.js which provides ways of writing logs to a specified file

  2. On a unix-based system, pipe the output of node to a file

    node my-file.js > output.txt

Sign up to request clarification or add additional context in comments.

1 Comment

The thing is I just want to run the .js file and the output needs to be stored in a txt file.Thanks anyways as the issue is resolved.
0
fs = require('fs');
fs.appendFile(__dirname + '/textFileName.txt', toString, function (err) {
    if (err) return console.log(err);
    console.log('Hello World > helloworld.txt');
});

1 Comment

Here how to pass my content that is in toString to 'Text to write'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.