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://imgur.com/o2Vo471
I'm wanting this printed as regular text to an output file e.g 'output.txt'
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');
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)
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
Related
I am trying to create a utility to take the windows relative path from VSCode or IntelliJ and replace the forward slash from the path with backslash and execute the jest command to produce the coverage of the files mentioned in the argument to a script.
This is what I tried:
Script_file.js
const yargs = require('yargs');
const exec = require('child_process').exec;
const options = yargs
.usage('Some info')
.option('t', {some_object})
.option('m', {some_object})
.argv;
const tp = options.t.replace(/\\/g, '/');
const mp = options.m.replace(/\\/g, '/');
exec(`jest ${tp} --coverage --collectCoverageFrom=${mp} --colors`, (error, stdout, stderr) => {
if(error){
console.log('err');
}
console.log(stdout);
})
My script in package.json
"test:CoverageFile": "node Script_file.js",
Command
npm run test:CoverageFile -- -t=windows\style\file\path\for\test -m=windows\style\file\path\for\file\to\get\coverage\from
Now, everything is fine and I'm getting the output as expected too except the marked area in the image attached below[Image is just for reference]:
My question is how can I print this table as well in the output? I'll be highly obliged for any help.
EDIT:
I also tried hooking up the --coverageReporters flag with jest command using various available options but to no avail.
I have
import fs from 'fs'
and in my package.json I have
Then I run the command
> npm i fs
> fs#0.0.2 node_modules/fs
next in my React store I import 'fs' module
import fs from 'fs'
However when I try to use fs
I don't see methods except for constructor and a few other __methods. I don't see the method createReadStream or any other file manipulation methods.
Does anybody know what is wrong? (using Webpack) and can give more information upon request, but I am getting this far...
ps: why is it that I can npm i fs --save when I read on other posts that I do not have to do that (using node 5.5.0)
import Reflux from 'reflux'
import AddItemActions from '../actions/AddItemActions'
import request from 'superagent-bluebird-promise'
import fs from 'fs'
var ImageStore = Reflux.createStore({
init(){
.
.
.
},
decryptImage(file) {
var reader = new FileReader();
var info = {}
reader.onload = (output) => {
debugger
request.post("https://camfind.p.mashape.com/image_requests")
.set("X-Mashape-Key", "KEY")
.set("Content-Type", "application/x-www-form-urlencoded")
.set("Accept", "application/json")
.send({'focus': { 'x': 480}})
.send({'focus': { 'y': 640}})
.send({'image_request': {'altitude': 27.912109375}})
.send({'image_request': {'language': "en"}})
.send({'image_request': {'latitude': 35.8714220766008}})
.send({'image_request': {'locale' : "en_US"}})
.send({'image_request': {'longitude': 14.3583203002251}})
.send({'image_request': {'image': fs.createReadStream("/path" + 'file.jpg')}})
.then(function (result) {
console.log(result.status, result.headers, result.body);
this.info = result
},
function(error) {
console.log(error);
})
}
reader.readAsDataURL(file);
return info
},
.
.
.
.
})
In create-react-app they have stubbed out 'fs'. You cannot import it.
They did this because fs is a node core module.
You'll have to find another solution to that problem. See this ticket.
It's possible this might be an environment issue. It's not possible for the browser to interpret and run some Node server-side modules like fs.
The solution is to run the fs methods in a Node environment (server-side) or to find a package which offers the same functionality but written for the browser.
It's discussed in this question...
Module not found: Error: Cannot resolve module 'fs'
And this question...
Use fs module in React.js,node.js, webpack, babel,express
npm i babel-plugin-preval
Though browser does not allow accessing file system during runtime, You can use prevail in React to read content from file system into memory during build time
like so
// loading content of text file into react project during build time.
// which means everytime text content is changed, you need to rebuild the project to get the updated content.
const greetingContent = preval`
const fs = require('fs')
module.exports = fs.readFileSync(require.resolve('./greeting.txt'), 'utf8')
`
console.log(greetingContent);
I use youtube-dl node driver to get information about videos on youtube, but I have trouble with ReferenceError - require is not defined (First line). I installed node-youtube-dl module on my laptop and the code is just taken from example in description. Is there anything else that I'm missing to do?
var youtubedl = require('youtube-dl');
var url = 'https://www.youtube.com/watch?v=9Q7Vr3yQYWQ';
ytdl.getInfo(url, function(err, info) {
if (err) throw err;
console.log('id:', info.id);
console.log('title:', info.title);
console.log('url:', info.url);
console.log('thumbnail:', info.thumbnail);
console.log('description:', info.description);
console.log('filename:', info._filename);
console.log('duration:', info.duration);
console.log('format_id:', info.format_id);
});
require() is a keyword in Node.js. It is used to import CommonJS modules like those in the npm registry. But it is not a keyword in your browser, where trying to use it will return a ReferenceError as you describe.
If you want to import npm modules using require() in your browser, you can try browserify or webpack. However, it is entirely possible (probable?) that youtube-dl is not compatible with browserify or webpack.
If you don't need to run it from a browser, you can put the code in a file (say, myFile.js) and run it from the command line with node:
node myFile.js
In your sample:
var youtubedl = require('youtube-dl');
However later you call it:
ytdl.getInfo(url, function(err, info)
just simply rename your require to ytdl, like this:
var ytdl = require('youtube-dl');
I'm trying to move a file from one partition to another in a Node.js script. When I used fs.renameSync I received Error: EXDEV, Cross-device link. I'd copy it over and delete the original, but I don't see a command to copy files either. How can this be done?
You need to copy and unlink when moving files across different partitions. Try this,
var fs = require('fs');
//var util = require('util');
var is = fs.createReadStream('source_file');
var os = fs.createWriteStream('destination_file');
is.pipe(os);
is.on('end',function() {
fs.unlinkSync('source_file');
});
/* node.js 0.6 and earlier you can use util.pump:
util.pump(is, os, function() {
fs.unlinkSync('source_file');
});
*/
I know this is already answered, but I ran across a similar problem and ended up with something along the lines of:
require('child_process').spawn('cp', ['-r', source, destination])
What this does is call the command cp ("copy"). Since we're stepping outside of Node.js, this command needs to be supported by your system.
I know it's not the most elegant, but it did what I needed :)
One more solution to the problem.
There's a package called fs.extra written by "coolaj86" on npm.
You use it like so:
npm install fs.extra
fs = require ('fs.extra');
fs.move ('foo.txt', 'bar.txt', function (err) {
if (err) { throw err; }
console.log ("Moved 'foo.txt' to 'bar.txt'");
});
I've read the source code for this thing. It attempts to do a standard fs.rename() then, if it fails, it does a copy and deletes the original using the same util.pump() that #chandru uses.
to import the module and save it to your package.json file
npm install mv --save
then use it like so:
var mv = require('mv');
mv('source_file', 'destination_file', function (err) {
if (err) {
throw err;
}
console.log('file moved successfully');
});
I made a Node.js module that just handles it for you. You don't have to think about whether it's going to be moved within the same partition or not. It's the fastest solution available, as it uses the recent fs.copyFile() Node.js API to copy the file when moving to a different partition/disk.
Just install move-file:
$ npm install move-file
Then use it like this:
const moveFile = require('move-file');
(async () => {
await moveFile(fromPath, toPath);
console.log('File moved');
})();
I'm trying to move a file from one partition to another in a Node.js script. When I used fs.renameSync I received Error: EXDEV, Cross-device link. I'd copy it over and delete the original, but I don't see a command to copy files either. How can this be done?
You need to copy and unlink when moving files across different partitions. Try this,
var fs = require('fs');
//var util = require('util');
var is = fs.createReadStream('source_file');
var os = fs.createWriteStream('destination_file');
is.pipe(os);
is.on('end',function() {
fs.unlinkSync('source_file');
});
/* node.js 0.6 and earlier you can use util.pump:
util.pump(is, os, function() {
fs.unlinkSync('source_file');
});
*/
I know this is already answered, but I ran across a similar problem and ended up with something along the lines of:
require('child_process').spawn('cp', ['-r', source, destination])
What this does is call the command cp ("copy"). Since we're stepping outside of Node.js, this command needs to be supported by your system.
I know it's not the most elegant, but it did what I needed :)
One more solution to the problem.
There's a package called fs.extra written by "coolaj86" on npm.
You use it like so:
npm install fs.extra
fs = require ('fs.extra');
fs.move ('foo.txt', 'bar.txt', function (err) {
if (err) { throw err; }
console.log ("Moved 'foo.txt' to 'bar.txt'");
});
I've read the source code for this thing. It attempts to do a standard fs.rename() then, if it fails, it does a copy and deletes the original using the same util.pump() that #chandru uses.
to import the module and save it to your package.json file
npm install mv --save
then use it like so:
var mv = require('mv');
mv('source_file', 'destination_file', function (err) {
if (err) {
throw err;
}
console.log('file moved successfully');
});
I made a Node.js module that just handles it for you. You don't have to think about whether it's going to be moved within the same partition or not. It's the fastest solution available, as it uses the recent fs.copyFile() Node.js API to copy the file when moving to a different partition/disk.
Just install move-file:
$ npm install move-file
Then use it like this:
const moveFile = require('move-file');
(async () => {
await moveFile(fromPath, toPath);
console.log('File moved');
})();