Trying to log to file on nodejs with 'log' package from npm - javascript

I'm not sure how I'm supposed to use this package. I've followed the example code from the docs:
var fs = require('fs')
, Log = require('log')
, log = new Log('debug', fs.createWriteStream('my.log'));
But then what? How do I send actual log info to the file? I want what normally gets logged with console.log() to go to the file.
edit: here's the context that I am using it in, as a minimal example. log.info() works fine outside of the while. As it is below, the file is created but has nothing in it.
var fs = require('fs')
var Log = require('log')
var log = new Log('info', fs.createWriteStream('my.log'));
while(true) {
log.info("testing");
}

// (taken from readme of package)
log.debug('preparing email');
log.info('sending email');
log.error('failed to send email');
These will each log to the file you specified. The function denotes the log level, and is prepended to the data you provide.

You need to use fs.appendFileSync() method in order to add content synchronously to the log you are creating.
var fs require('fs')
,Log = require('log')
,log = new Log('debug', fs.createWriteStream('test.txt'));
log.debug('test test');
log.debug('test sadasd');
log.debug('test xcvxcv');
log.debug('test ewrewr');
log.debug('test hjgj');
log.debug('test fghfh');
log.debug('test yuiyui');

This package is not designed to log Console.log() statement. As per my knowledge every log file have date/time/(log type) and information related to it. So normal console.log() also have same info stored into it.
Log package which you mentioned is used to create user defined logs of any type (info,debug,warning etc etc.).

Related

How to execute a function on the node server by using vanilla javascript

Okay so basically I'm trying to create a typing game that uses a JSON file as the database. I'm using Nodejs to manipulate the use of a .json file with the fs module. What I want to do is have a main.js which operates the website's appearance which will contain a table of high scores, and I also want a player.js which will run on the back-end which updates a JSON file containing each player's name and high score.
So I was experimenting with it. I learned the hard way that require() is a node function. I want main.js to call a function from player.js and send it parameters.
var playerArr = player.updatePlayers("Rain", 30);
I know this doesn't work but the updatePlayers() function written with node in player.js returns an array and I want to set it to playerArr within main.js.
require() comes up with an error in the browser because its not a part of vanilla Javascript and I know it has to be run on a node server.
Is there any way to do this? It's for a school project and I'd love to be able to implement Nodejs and JSON into it.
Okay so everything's working except one crucial thing... the array isn't being sent back to the browser. I decided to use routes from express:
app.get("/:name,:score", returnScoreboard);
function returnScoreboard(request, response){
let data = request.params;
playerArr = updatePlayers(data.name, data.score);
response.send(playerArr);
}
Now in my main.js, this is my code:
var playerArr;
var updatePlayer = new XMLHttpRequest();
updatePlayer.onreadystatechange = () => {
playerArr = this.responseText;
}
updatePlayer.open("GET", "/Moo,100", true);
updatePlayer.send();
console.log(playerArr);
And I can't seem to get a response from into the playerArr. The JSON file that I'm using is getting updated correctly with a new object every time ({"name":"Moo", "score":100}) but it's not being assigned to playerArr. Please help!
I suggest you have a Node backend and use something like https://expressjs.com/. You can use it to set up some endpoint(s). These endpoints would be called upon by your frontend JS code using Fetch or something of the like, https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.
Response to the edits above:
I think you are probably facing an asynchronous issue. I just moved the console.log into the onreadystatechange call. The onreadystatechange executes whenever a response comes back from the server, so by the time your code got to the original console.log the onreadystatechange may not have fired.
var playerArr;
var updatePlayer = new XMLHttpRequest();
updatePlayer.onreadystatechange = () => {
playerArr = this.responseText;
console.log(playerArr);
}
updatePlayer.open("GET", "/Moo,100", true);
updatePlayer.send();

How can you use variables defined in node.js in client side js?

I'm having problems with using 'pairs' in my java script file, more specifically whenever I run the code pairs is not defined. I have tried everything i can think of and this is what i think should work:
This is my node.js file:
const fs = require('fs');
let data = fs.readFileSync('inputs.txt', 'utf8').split('\n');
global.pairs = data;
And this is my java script file:
console.log(pairs)
Obviosly it doesn't work and instead of an array of inputs i get an error. I cannot just do the console.log in node.js because i need the inputs for other things that cannot be done in node. Thank you for your help.

writeSync() only writes to the console when console.log is present (node.js)

Take the following snippet:
try {
fs = require('fs');
fs.writeSync(0, 'Trying now...');
fs.writeSync(0, 'worked!\r');
}
catch(error){}
As is, it will not output to the console, however
try {
fs = require('fs');
fs.writeSync(0, 'Trying now...');
fs.writeSync(0, 'worked!\r');
console.log();
}
catch(error){}
Will output "Trying now... worked!" to the console. What exactly is going on here?
You're writing to the file descriptor but are not flushing it. Writing a line break (\n instead of \r) does lead to stdout flushing its buffer, as well as a console.log() call that forces it.
Just realized it was because I was using \r instead of \n

Print Image in Server side on Button Click by Client [duplicate]

Ok, so I'm trying to print from a webpage (the typical "print" button, but I don't want the print dialog to appear) so I decided to use my already existing node.js backend to do the task (mainly because printing from browser is nearly impossible without the printing dialog).
I found the node-printer (https://github.com/tojocky/node-printer) module, and it works great, but only with text. I tried to send RAW data, but what it does is printing the raw characters. What I actually need is to print a logo, along with some turn information (this is for a customer care facility).
Also, the printer must be installed locally, so I can't use IPP.
Is there any way to print an image, or a combination of images and text with node.js? can it be done through node-printer or is there another way?
I ended calling an exe to do the work for me. I use a child_process to call printhtml, which does all the printing work for me. My code ended this way:
var exec = require('child_process').exec;
exec('printhtml.exe file=file.html', function(err, data) {
console.log(data.toString());
});
Actually, you can print image using node-printer. This work for me
var Printer = require('node-printer');
var fs = require('fs');
// Get available printers list
var listPrinter = Printer.list();
// Create a new Pinter from available devices
var printer = new Printer('YOUR PRINTER HERE. GET IT FROM listPrinter');
// Print from a buffer, file path or text
var fileBuffer = fs.readFileSync('PATH TO YOUR IMAGE');
var jobFromBuffer = printer.printBuffer(fileBuffer);
// Listen events from job
jobFromBuffer.once('sent', function() {
jobFromBuffer.on('completed', function() {
console.log('Job ' + jobFromBuffer.identifier + 'has been printed');
jobFromBuffer.removeAllListeners();
});
});
I had success with the Node IPP package https://www.npmjs.com/package/ipp.
The example code on the docs, which uses another node module PDFKIT to convert your html/file into a PDF, does not work. See my answer here: Cannot print with node js ipp module for a working example.

Logging in node.js to a file, without another module

I'm running a node application as a daemon. When debugging the daemon, I need to see the output, so I'd like to redirect stdout and stderr to a file.
I'd expect I can just reassign stdout and stderr like in Python or C:
fs = require('fs');
process.stdout = fs.openSync('/var/log/foo', 'w');
process.stderr = process.stdout;
console.log('hello');
When I run the script directly, "hello" is printed to the console! Of course when I run in the background, I see output neither on the console (of course) or in /var/log/foo.
I don't want or need sophisticated logging. I just need to see the builtin messages that node already provides.
The console object grabs a reference to process.stdout and stderr when it is first created.
(you can see this in the source).
Re-assigning them later does not affect console.
The usual way to redirect these streams is to launch the process with the streams redirected.
Alternatively, you can overwrite the console methods and make them write to your file instead.
Similar to this question, you can overwrite process.stdout.write which is called from console.log.
var fs = require('fs');
var oldWrite = process.stdout.write;
process.stdout.write = function (d) {
fs.appendFileSync('./foo', d);
oldWrite.apply(this, arguments);
};
console.log('hello');

Categories