Can a nodeJs script delete his own file? - node.js

I'm working on an updater and I wish there is some way for the updater to update itself (remove and copy the new file from which the script is run).
Is it possible?
Is it a good practice?
Have you got an advice for such a situation?

Is it possible ? Yes...
Is it a good practice ? It depends, if you are updating an application, it could be a good approach...
Have you got an advice for such a situation ? Not actually because if you need a new version of your app you must update the files but I would suggest a parallel app who is in charge of updating the main app...
Example:
var fs = require('fs');
console.log("I'm about to delete myself...");
console.log('clonning myself...');
fs.copyFileSync('./selfDelete.js', './selfDelete_bkp.js');
console.log('removing myself...');
fs.unlinkSync('./selfDelete.js');
console.log('new version of me...');
fs.renameSync('./selfDelete_bkp.js', './selfDelete.js');

Not a good practice.
And you cannot update while you running.
What I can suggest is you can create a new file somewhere with updates and then replace the current file with the new file from a scheduled task which runs sometime later.
Not sure that answered your question but this is what I can think of.

Related

Is it possible to close a Puppeteer Browser using its contextId?

This is an update to a question I had asked previously but wasn't thinking straight when I asked the question (I was taking a very backwards approach to my solution). I'm currently working with Puppeteer and I'm trying to create an association between a particular task and a puppeteer browser instance. Right now I am currently getting the browser's context id using:
const {browserContextId} = await browser._connection.send('Target.createBrowserContext');
and I am storing it in a file along with other details related to the task. My goal is to somehow be able to close that browser instance using the stored context id. I've given this issue a read on the Puppeteer's GitHub hoping that it would help in some way but it seems that it's not super helpful to me as its not really related to what I'm doing.
The real issue is that I am going to be spawning browser instances in one file and attempting to close them in another, otherwise this wouldn't be an issue at all. Right now the only thing I've been able to do is just spawn another browser instance using the context id (pretty much useless for my task) and have had no luck in closing it or disposing it.
Any help would be greatly appreciated, thanks!
P.S. If there is a better approach to solving this association issue I'm all ears!
Turns out I was thinking about it way too much and trying to make it too complex. For anyone trying to do something similar I'll leave my solution here for you.
Instead of using the browser's context id I found it much easier to just grab the browser's process id (pid). From there I could kill the process using different strategies based on where I was running the close command.
For Node.js:
// Lets say for example we're instantiating our browser like this
const browser = await puppeteer.launch({ headless: false });
// You can simply run this to get the browser's pid
const browserPID = browser.process().pid
// Then you can either store it for use later
fs.writeFile(file, JSON.stringify(jsondata, null, 4), (err) => {
if (err) console.log(err);
})
// Or just kill the process
process.kill(browserPID);
Keep in mind that if you are storing the PID you need to read the file and parse the data to pass into the process.kill command.
For React via Electron
// Require process from the electron file
const process = window.require('process');
// Then same process as before
process.kill(yourbrowserPID);
Hopefully my stupidity can help someone in the future if they are trying to do something similar. It was way easier than I was making it out to be.

Firebase Database - Variable Child (Android Studio)

I need help. Is there any way to make a child in the firebase database from android studios with a variable? I want to create a child with text that the user enters into the application and it is saved in a variable.
Etc.: mFirebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(MailVariable)
I try this line of code but my app was crash every time.
Is there any way? Please answer or refer me to the site where the solution is located.
Thank you.
(Note: I'm beginner and I'm getting ready for competition)
if your mFirebaseDatabase variable returning an instance of the FirebaseDatabase then that is wrong. Be careful with the return types of the sdks.
FirebaseDatabase.getInstance().getReference().child("Users").child(MailVariable)
the above will not return a type of FIrebaseDatabase
Yes you can! But you have to set value of that particular child too.

My Discord.js bot uses a command handler. How can I then create play/skip/pause/resume/etc commands in different files?

I set up the command handler for my bot using the Discord.js guide (I am relatively new to Discord.js, as well as JavaScript itself, I'd say). However, as all my commands are in different files, is there a way that I can share variables between the files? I've tried experimenting with exporting modules, but sadly could not get it to work.
For example (I think it's somewhat understandable, but still), to skip a song you must first check if there is actually any audio streaming (which is all done in the play file), then end the current stream and move on to the next one in the queue (the variable for which is also in the play file).
I have gotten a separate music bot up and running, but all the code is in one file, linked together by if/else if/else chains. Perhaps I could just copy this code into the main file for my other bot instead of using the command handler for those specific commands?
I assume that there is a way to do this that is quite obvious, and I apologize if I am wasting peoples' time.
Also, I don't believe code is required for this question but if I'm wrong, please let me know.
Thank you in advance.
EDIT:
I have also read this question multiple times beforehand and have tried the solution, although I haven't gotten it to work.
A simple way to "carry over" variables without exporting anything is to assign them to a property of your client. That way, wherever you have your client (or bot) variable, you also have access to the needed information without requiring a file.
For example...
ready.js (assuming you have an event handler; otherwise your ready event)
client.queue = {};
for (guild of client.guilds) client.queue[guild.id] = [];
play.js
const queue = client.queue[message.guild.id];
queue.push({ song: 'Old Town Road', requester: message.author.id });
queue.js
const queue = client.queue[message.guild.id];
message.channel.send(`**${queue.length}** song${queue.length !== 1 ? 's' : ''} queued.`)
.catch(console.error);

nodejs browser-sync - logging

im very new to nodejs but was wondering if the following was easily possible to achieve.
I use Gulp along with browser-sync plugin. I was wondering if there was a way to log every time the browser gets re-injected with the domain and time over a port range. The reason for this being I want to be able to plot productivity over projects without having to manually record this and this seems to be the most logical solution.
Is there anything out there like this or could this easily be added into a Gulp file?
Many thanks, Luke
There are some options and you can use the emitter to react to events like stream:changed, browser:reload, client:connected, connection,...
example:
var bs = require("browser-sync").create();
bs.init({}); //http://www.browsersync.io/docs/options/
....
bs.emitter.on("file:reload", function(){
console.log("File reload - Details:"+arguments)
});

is it possible to read /proc/{pid}/stat then transfer to client real time?

suppose i want to monitor mysql, as far as i know, all mysql runtime info is stored in /proc/{mysql_pid}/stat. so is it possible to read and parse mysql stat info via node.js and client display the chart real time ?
nagios and alternative is so heavy, and sometimes i just want to monitor some progress info. so i want a lightweight solution.
I tried using Node Inotify, which is an excellent library. Yet, it seems like the proc filesystem doesn't event to inotify when the stat files are changed. If you're watching a file on a normal filesystem, though, this is how you can do it using that library:
sys = require('sys');
fs = require('fs');
Inotify = require('inotify').Inotify;
var inotify = new Inotify();
function callback(ev) {
console.log(sys.inspect(ev));
}
var home_dir = {
path: '/proc/5499/stat'
, watch_for: Inotify.IN_ALL_EVENTS
, callback: callback
};
var home_watch_descriptor = inotify.addWatch(home_dir);
Just change Inotify.IN_ALL_EVENTS to whatever action you want to watch for, which is documented on the github page I linked.
Sorry this doesn't solve your particular problem, but I thought I'd post it informationally.
I'm assuming you haven't tried implementing a solution to your problem. What exactly do you mean by "real time"? What sort of client are you talking about?
If you're talking about a web browser client, there's no reason you couldn't update some sort of display every half-second with loads of clients (or much faster, if the charts aren't too intricate).
You should be more specific if you want a more specific answer than that.

Resources