Reputation: 379
I'm trying to print the result of my console.log to another .txt file, how would I make this happen? this is what my console.log looks like this: https://i.sstatic.net/pYY00.jpg
I'm wanting this printed as regular text to an output file e.g 'output.txt'
Upvotes: 0
Views: 2043
Reputation: 4457
I recommend to use Winston to achieve this.
You can set up Winston Transports to output in file winston.add(winston.transports.File, options)
Or if you don't wanna add any npm modules to your app you can just do this
var fs = require('fs');
module.exports = function(text) {
fs.appendFile('output.txt', text + '\n', function (err) {
if (err) throw err;
});
};
And save this to a file in your project directory, for example NameOfYourFile.js.
Then you can just require it in a file that you wanna make output from
var loger = require('./NameOfYourFile');
loger('Logs');
loger('Output');
loger('Working');
And just use loger instead of console.log. You also can easily rename it.
TypeScript version
First, install node modules
npm install @types/node --save-dev
Then create a file for your module, for example, NameOfYourFile.ts
import * as fs from 'fs';
export default function(text) {
fs.appendFile('output.txt', text + '\n', function (err) {
if (err) throw err;
});
};
Then you can import it like this
import loger from './NameOfYourFile';
loger('Logs');
loger('Output');
loger('Working');
Upvotes: 1
Reputation: 379
This answer works, but it isn't what i'm aiming for it will work for most other people i'd assume. you're gonna want to run your program like so:
npm start > output.txt
this will print your console output to the output.txt file I still need to achieve this with node fs so i'd appreciate anymore answers
Upvotes: 0
Reputation: 1109
Can you rewrite your program as a node app and then just run it from the Terminal window instead? Then, you wouldn't need to wrestle with this problem of getting your console output into a file... you could use node's fs instead (Node.js Write a line into a .txt file)
Upvotes: 0