How can I trigger Rollup's "watchChange" hook in a vite plugin? - vite

I currently have a plugin that tracks the buildStart and buildEnd of my vite instance. I want to also track the recompile time when a user makes changes to a file. This is my current plugin (calling watchChange this way does not log anything to the console on a file change).
let endTime = null;
function Plugin() {
let startTime = null
return {
name: 'my-plugin',
buildStart() {
startTime = new Date()
},
watchChange: (id) => {
console.log("This does not log when I save/make changes to a file listed in the inputs section of my vite config");
},
buildEnd() {
endTime = new Date();
}
}
}

Related

Trigger a function at particular time everyday in javascript

I'm creating a birthday app where I want to trigger a function at a particular time Eg. At 6 AM. But I'm not getting any idea of how to implement that. Please give a suggestion. Using react as frontend and express as backend and database I use MongoDB. Also, any code reference will help .Thank you in advance.
You can try smth like this, after component rendered setInterval function will check if it is your birthday now or not.Finally, in right moment will invoke some func and disable itself.
import React, { useEffect } from 'react';
const BirthDay = () => {
const date = new Date('2022-12-17T03:24:00') //your birthday here
const birthdayFunc = () => {console.log('Birthday!!!')}
const checkBirthday = () => {
if(new Date() >= date) birthdayFunc()
else return
}
useEffect(
() => {
const id = setInterval(function()
{
if(new Date() >= date)
{
birthdayFunc()
clearInterval(id)
}
else return
}, 1000);
return () => clearInterval(id);
},
[]
);
return <div></div>;
};
A solution can be using a job scheduler such as crontab on Linux machine. If its Windows, cron is called scheduled tasks and It's in the Control Panel. It allows to trigger periodically perform a task.

Node.js read file from disk

I want to write NP music in discord status. Google Play Music Desktop Player has a playback.json file, I need to check this file in my node.js and change music in discord status. At this moment I have this code for checking this file
const fs = require(`fs`)
var song = [];
check();
function check() {
fs.readFile("C:\\Users\\lensh\\AppData\\Roaming\\Google Play Music Desktop Player\\json_store\\playback.json", (err, data) => {
let playback = JSON.parse(data)
console.log(`Checking...`)
if(playback.playing !== `true`) return setTimeout(() => {check()}, 10000), console.log(`IDLE.`), idle();
else {
if(song.includes(playback.song.title)) return setTimeout(() => {check();}, 10000), console.log(`Waiting...`), console.log(song), console.log(playback.song.title);
else {
song.splice(0, song.length);
song.push(playback.song.title);
status(playback.song.artist, playback.song.title);
setTimeout(() => {check();}, 15000)
}
}
});
}
Problem is that node.js reads the file only on the startup, then node.js didn`t check this file for any changes. How to solve this problem?
P.S. Sry for my english
You don't need to do manually. You can use the node.js watch file API and load the file on change.
const fs = require("fs")
let lastUpdated = new Date()
fs.watchFile("./test.json", (curr, prev) => {
if(curr.mtime.getTime() - lastUpdated.getTime() > 2 *1000) { // after 2 min
// DO something here
console.log(`the current mtime is: ${curr.mtime}`);
lastUpdated = curr.mtime
}
})
Ref: https://nodejs.org/docs/latest/api/fs.html#fs_fs_watch_filename_options_listener
You may need to watch the file change and let's your function run.
https://thisdavej.com/how-to-watch-for-files-changes-in-node-js/

How can you record a `.har` of an Electron `webContents` session?

I have a Javascript application that spawns Electron and does a bunch of stuff in it.
I'm trying to debug a strange network issue I'm having, and to do this, I'd like to use a HAR file to store a log of all the HTTP requests being made by Electron.
Is this possible?
Yes, it can be done using chrome-har-capturer - you can pass a bunch of events from the webContents.debugger and then chrome-har-capturer will transform them into a HAR for you.
Example code:
const chromeHarCapturer = require('chrome-har-capturer')
let log = []
const webContents = browserWindow.webContents
webContents.debugger.on("message", function(event, method, params) {
// https://github.com/cyrus-and/chrome-har-capturer#fromlogurl-log-options
if (!["Page.domContentEventFired", "Page.loadEventFired", "Network.requestWillBeSent", "Network.dataReceived",
"Network.responseReceived", "Network.resourceChangedPriority", "Network.loadingFinished",
"Network.loadingFailed"].includes(method)) {
// not relevant to us
return
}
log.push({method, params})
if (method === 'Network.responseReceived') { // the chrome events don't include the body, attach it manually if we want it in the HAR
webContents.debugger.sendCommand('Network.getResponseBody', {
requestId: params.requestId
}, function(err, result) {
result.requestId = params.requestId
log.push({
method: 'Network.getResponseBody',
params: result
})
})
}
})
webContents.debugger.once("detach", function() {
// on detach, write out the HAR
return chromeHarCapturer.fromLog("http://dummy-url-for-whole-session", log).then(function(har) {
const path = `/tmp/${Number(new Date())}-har.json`
fs.writeJson(path, log)
log = []
})
})
// subscribe to the required events
webContents.debugger.attach()
webContents.debugger.sendCommand('Network.enable')
webContents.debugger.sendCommand('Page.enable')

CRM JS event for field value changed by workflow

I have form and button on that form in CRM 2015. By clicking on button on form, user triggers on-demand workflow. When workflow is done, it updates value of one of the fields on the form. However, this server data change is not reflected on the user UI.
What is the best way to register JS callback which will refresh form if workflow execution is successful?
Reading this: https://msdn.microsoft.com/en-us/library/gg334701.aspx it looks like I can't use OnChange() event, because I change data programatically.
First of all I would suggest to use Sync Workflow. After workflow is executed just execute following code:
Xrm.Page.data.refresh(false);
I had such requirements once. I had to reflect changes on the Form that are changed by the Async Workflow, and for some reason i had to keep the Workflow Async.
Following is a work-around i did for requirements like this.
Add a new field to the entity, on which the workflow is executed.
FieldName: "isworkflowexecutedsuccessfully"
FieldType: "TwoOption"
Default Value: "false"
Then in your code where you have written the workflow code, write this:
function someFunctionOfYours() {
RunWorkflow(); //
WaitForWorkflowToCompleteProcessingAndThenReload();
}
function isWorklowExecutionCompleted(TimerId, updateIsWorkflowExecutedSuccessfully) {
var entityName = Xrm.Page.data.entity.getEntityName();
var entityGuid = Xrm.Page.data.entity.getId();
var retrievedOpportunity = XrmServiceToolkit.Soap.Retrieve(entityName, entityGuid, new Array("isworkflowexecutedsuccessfully")); //synchronous call
if (retrievedOpportunity.attributes["isworkflowexecutedsuccessfully"].value = true) {
clearInterval(TimerId);
setTimeout(function () {
setIsworkFlowExecutedSuccessfullyToFalse(updateIsWorkflowExecutedSuccessfully);
}, 3000);
}
}
function WaitForWorkflowToCompleteProcessingAndThenReload() {
var TimerId = setTimeout(function () {
isWorklowExecutionCompleted(TimerId);
}, 5000);
}
function setIsworkFlowExecutedSuccessfullyToFalse(updateIsWorkflowExecutedSuccessfully) {
var entityName = Xrm.Page.data.entity.getEntityName();
var entityGuid = Xrm.Page.data.entity.getId();
var updateOpportunity = new XrmServiceToolkit.Soap.BusinessEntity(entityName, entityGuid);
updateOpportunity.attributes["isworkflowexecutedsuccessfully"] = false;
if (updateIsWorkflowExecutedSuccessfully == false || updateIsWorkflowExecutedSuccessfully == null) {
XrmServiceToolkit.Soap.Update(updateOpportunity);
}
Xrm.Utility.openEntityForm(entityName, entityGuid) //refresh form
}

Persist data on disk using chrome extension API

I am trying to save some data which should be available even when restart the browser So this data should persist. I am using Chrome Storage Sync API for this. But when I am restarting my browser, I get empty object on using chrome.storage.get.
Here is my sample code:
SW.methods.saveTaskListStore = function() {
chrome.storage.sync.set({
'taskListStore': SW.stores.taskListStore
}, function() {
if (SW.callbacks.watchProcessSuccessCallback) {
SW.callbacks.watchProcessSuccessCallback(SW.messages.INFO_DATA_SAVED);
SW.callbacks.watchProcessSuccessCallback = null;
}
});
};
SW.methods.loadTaskListStore = function() {
SW.stores.loadTaskListStore = [];
chrome.storage.sync.get('taskListStore', function(taskFeed) {
var tasks = taskFeed.tasks;
if (tasks && !tasks.length) {
SW.stores.loadTaskListStore = tasks;
}
});
};
I guess I am using the Wrong API.
If this is not some copy-paste error, you are storing under key taskListStore and trying to get data under key loadTaskListStore.
Besides that, according to the documentation on StorageArea.get(), the result object is an object with items in their key-value mappings. Thus, in your case, you should do:
chrome.storage.sync.get("taskListStore", function(items) {
if (items.taskListStore) {
var tasks = items.taskListStore.tasks;
...

Resources