Logging variable in nodejs - node.js

I have a variable named, 'res'. This variable if used with console.log() print all request to a function. My question is... How to log this variable in a log.txt file?
Example using console.log(res)
Print in console:
[ 'AndroidShareANE',
'pixi.js',
'ShortSword',
'faceshiftparser',
'clmutils',
'chaikin-smooth',
'getuservideo',
'getboundingbox',
'clmdraw',
'SpriteSheetScrubberTutorial',
'interpolation-arrays',
This is a one part of response.
My purpose is log in log.txt file the var content. Identical to console.log() result.
Thanks for your collaboration, and sorry my bad english.

The easiest way is to create a new Console object that writes to your file. The docs have an example of this exact thing, which I'll reproduce here for posterity:
const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger
const logger = new Console(output, errorOutput);
// use it like console
var count = 5;
logger.log('count: %d', count);
// in stdout.log: count 5
If you don't pass the second argument (errorOutput) to new Console then the error output will also be written to the output file.

Related

Using script + screen through child_process

Solved:
I had to add \r\n at program.stdin.write(data) (something like this program.stdin.write(data+'\r\n')) and it worked.
It seems that if i don't put \r\n, it doesn't triggers, its like typing in a line without pressing enter so it will never be processed.
===========================================================================
I need to access screen through child_process, but it doesn't works properly.
First I tried to access using spawn.
const {spawn} = require('child_process');
const program = spawn('screen',['-x User/Aplication']);
program.stdout.on('data',data=>{
//Something
})
function writeTo(data){
program.stdin.write(data);
}
But i got the error "Must be connected to a terminal error". After some research i found a solution, use script+spawn to make a pseudo-console.
const {spawn} = require('child_process');
const program = spawn('script',['/dev/null']);//Pseudo-console
program.stdin.write('screen -x User/Aplication');//I access to screen through the pseudo-console, and it works.
program.stdout.on('data',data=>{
//Something
})
function writeTo(data){
program.stdin.write(data);
}
But... when I try to use writeTo, it doesn't works.
writeTo('Some command here')//Does nothing.
And somehow, when I pipe my console input, it works!
process.stdin.pipe(program.stdin);
Then I type something in my console and it proxies properly to connected screen.
Issue: It doesn't proxies properly when using program.stdin.write, but somehow, it works when i pipe my console process.stdin.pipe(program.stdin)
Observation 1: I made a short echo-program and it worked with both program.stdin.write and process.stdin.pipe(program.stdin)
echo.js
process.stdin.on('data',data=>{
console.log(`[Input]${data}`);
})
main.js
const {spawn} = require('child_process');
const program = spawn('node',['echo.js']);
program.stdout.pipe(process.stdout);
function writeTo(data){
program.stdin.write(data);
}
writeTo('Test');//Output: [Input]Test
process.stdin.pipe(program.stdin);//I type 'something'. Output: [Input]something
Observation 2: When using script+screen and piping my console, program.stdin.write only 'buffers' and process.stdin.pipe loads that buffer and sends it with what i typed.
program.stdin.write('He');//screen receives nothing
program.stdin.write('llo');//screen receives nothing
process.stdin.pipe(program.stdin);//I type ' world!'. screen receives 'Hello world!'
it may not be the whole problem, but the second argument to spawn should have each argument in a separate array element.
const program = spawn('screen',['-x', 'User/Aplication']);
I had to add \r\n at program.stdin.write(data) (something like this program.stdin.write(data+'\r\n')) and it worked.
It seems that if i don't put \r\n, it doesn't triggers as a new line and it doesn't sends it, its like typing all commands in a line without pressing enter so it will never be processed.

module.exports variable producing undefined result

So one of the features of the bot I am working on is that I can be on discord 'discreetly', meaning that I can have the idle status but if a friend knows what command to call, they can actually check if I am there. So in my index file I am using module.exports to store the variable that will contain the info that I set. In the other file, I have an array of values that depending on the value from the variable, the bot will respond with one of the phrases from the array. The problem is that when using the variable, I get an undefined response. Any ideas what I am doing wrong? Important to note
I have checked to make sure by putting an actual number and have gotten the correct response so it is an issue with the exporting. I also have the correct file path. I have also assigned variable info a number and gotten the same result. Edit: tried using the filepath as part of the variable in the array like so and got the same error
//This got me a new result so progress.
const filepath = filepath;
console.log(filepath); //This gets me {}
message.reply(activity[info]); //undefined
//new attempt that failed
//paraphrasing the filepath assignment
const filepath = filepath;
activity[filepath.info]
//first attempt
//from index
var info = message.content;
module.exports = info;
//from the other file
var activity = ["Ready to play","Chilling","Doing work","afk","can talk"];
console.log(activity[info]);
message.reply(activity[info]);
how to get a variable from a file to another file in node.js
So this is the solution to my problem
//index
var info = message.content;
module.exports.info = message.content;
//other file
const filepath = filepath;
var activity = [array of different values];
message.reply(activity[index.info]);
Thank you slothiful for you time in trying to help me. I really appreciate it

Node.js pass text as stdin of `spawnSync`

I'd think this would be simple, but the following does not work as expected.
I want to pipe data to a process, say (just an arbitrary command for illustration) wc, from Node.
The docs and other SO questions seem to indicate that passing a Stream should work:
const {spawnSync} = require('child_process')
const {Readable} = require('stream')
const textStream = new Readable()
textStream.push("one two three")
textStream.push(null)
const stdio = [textStream, process.stdout, process.stderr]
spawnSync('wc', ["-c"], { stdio })
Unfortunately this throws an error:
The value "Readable { ... } is invalid for option "stdio"
The relevant bit of code from internal/child_process.js does not immediately reveal what the anticipated valid options are.
To present particular data as stdin data for the child process, you can use the input option:
spawnSync('wc', ['-c'], { input : 'one two three' })

returning result from another nodejs file

i am working on a project in which a nodejs program calls another program in a separate file.
this is how i've added the two:
var ocr = require('./index.js'); //this imports the file
var arr = ocr.ocr_pan(); //this calls the function in that file
am not sure but I guess the problem is that the process resumes before ocr.ocr_pan() returns the result and var arr becomes undefined.
or there is some problem in returning the result from ocr.ocr_pan()
I simply use return.
and I have also tried this : How to return array from module in NodeJS
didn't work
what more can be done?
Assuming that this file is the same directory as index.js file, code in index.js should be something like this:
// Write your function
var ocr_pan = function() {
// Do whatever you like
return result;
};
// Export it, make publicly visible to other files
module.exports = {
ocr_pan: ocr_pan
};

How does this npm build work?

https://github.com/apigee-127/swagger-converter
I see this code:
var convert = require('swagger-converter');
var fs = require('fs');
var resourceListing = JSON.parse(fs.readFileSync('/path/to/petstore/index.json').toString());
var apiDeclarations = [ JSON.parse(fs.readFileSync('/path/to/petstore/pet.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/user.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/store.json').toString())
];
var swagger2Document = convert(resourceListing, apiDeclarations);
console.log(JSON.stringify(swagger2Document, null, 2));
I'm confsued as to what exactly I'm supposed to do here to run this? Do I start a node http server?
To run the file you pasted, just save the code into a file like script.js. Then from the command line (with node installed) run node script.js. That will run the file. Here's a breakdown of what it's doing:
var convert = require('swagger-converter');
This line gets reference to the swagger-converter module that you linked to. That module is designed to allow you to convert swagger documents into JSON.
var fs = require('fs');
This line gets reference to the node built-in filesystem module (fs for short). It provides an API for interacting with the filesystem on your machine when the script is running.
var resourceListing = JSON.parse(fs.readFileSync('/path/to/petstore/index.json').toString());
This line could be broken down to:
var indexContent = fs.readFileSync('/path/to/petstore/index.json');
JSON.parse(indexContent.toString());
readFileSync returns the contents of the index.json file as a buffer object, which is easily turned into a simple string with the call to .toString(). Then they pass it to JSON.parse which parses the string and turns it into a simple JavaScript object.
Fun Fact: They could have skipped those steps with a simple var resourceListing = require('/path/to/petstore/index.json');. Node knows how to read JSON files and automatically turn them into JavaScript objects. You need only pass the path to require.
var apiDeclarations = [ JSON.parse(fs.readFileSync('/path/to/petstore/pet.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/user.json').toString()),
JSON.parse(fs.readFileSync('/path/to/petstore/store.json').toString())
];
This bit of code does the same thing as the resourceListing except it creates an array of three JavaScript objects based on those JSON files. They also could have used require here to save a bit of work.
Then finally they use the converter to do the conversion and then they log that data to the terminal where your script is running.
var swagger2Document = convert(resourceListing, apiDeclarations);
console.log(JSON.stringify(swagger2Document, null, 2));
JSON.stringify is the opposite of JSON.parse. stringify turns a JavaScript object into a JSON string whereas parse turns a JSON string into a JavaScript object.

Resources