Initialization PostgreSQL with Node Js - javascript

I'm trying to delete some entries based on the creation/expiry date in a PostrgreSQL DB only at the beginning, when the node server starts.
At present I put the line
DELETE FROM ....db WHERE date <= CURRENT_DATE
in the main route and it works, but that also mean that each time I refresh the page Node gets to execute that line, over and over again.
Is there a way to add a functionality for which the database knows and executes that line only once at the very beginning?
Should I create a different javascript function that fires at the beginning of the server.js file?
I'm using PostgreSQL, NodeJs and Express (no sequelize or similar).
Thanks.

Should I create a different javascript function that fires at the beginning of the server.js file?
Yes.

JavaScript is a scripting language, which means that the code gets executed in the outer block (global scope). There is no main() function as in C/C++. So you should just put this line after the database initialization code in the outer program scope.

Related

How to use the npm module gs1-barcode-parser?

I want to extract the price value from the GS1 data martix QR code value using Nodejs.
Using the module
npm i gs1-barcode-parser
Tried the below throwing "parseBarcode" is not a function
const { parseBarcode } = require('gs1-barcode-parser');
let barcode = '\u001d01093393871222863922001405\u001d1522030631030006691095751410';
console.log(parseBarcode(barcode));
I would use the modded module gs1-barcode-parser-mod2
const parser = require("gs1-barcode-parser-mod2")
let barcode = ']C101040123456789011715012910ABC1233932978471131030005253922471142127649716';
console.log(parser.parseBarcode(barcode));
Unfortunately your barcode seems to be invalid. You will need to decode from UTF-8 as that would result in ∞01093393871222863922001405∞1522030631030006691095751410 even then your barcode seems to have a missing prefix, called an Application Identifier or for short, AI (]xxxxx..).
A valid barcode example is given in the code snippet above.
More info about application identifiers
So your trying to import a module to a CJS environment, but the module is written to resolve as a front end JavaScript Module.
Fortunatly the package contains a single source file, with a single IIFE function.
THIS WILL MAKE IT AN EASY FIX!
Please note though, it is only one file & one function, but the file, and the function are really big for being a single file & a single function, so big, that it wouldn't be impracticable to add them as a snippet in a Stack Overflow answer, consequently; I have created a repository, and added the source code, that works as a solution for this problem, to the repository. I have outlined the changes that one needs to make to the module, to get it to work on the backend (in the Node REPL).
The files I added to my REPO should work for your current needs though. Continue Reading
To Convert The Module you Need to do the Following...
What you need to do is convert the package single source file into a Node module, which is very easy. The file is far to long to add to a Stack Overflow answer. So what I have done, is I have added the file into a public GitHub repository located HERE.
Go to the link to the file I rewrote
The file is a module conversion of this file.
Look at both files so you can see how I made the change.
In a nutshell, the author of the module wrote it using whats called an
IIFE: Immediately Invoked Function Execution
Its a type of function that is invoked immediately. The purpose of the function is to invoke at the very start of a script being loaded. IFFE's load before anything else, which is why he was using it to load his frontend module.
 
The Entire Module is One function, and the whole thing is wrapped like the example below:
(function (){
// Function Logic Here.
})();
Basically, what I did, is I unwrapped it, and appended a module.export.BarcodeParser assignment to the function.
To reiterate: Go Get the new File (or technically its written as a CJS module) from the Repo I Created
At This Point, Just Follow the Steps Below.
Create a new Node.js project, and make sure you execute npm init to generate a properly formatted package.json file.
Test the converted module: To test the file w/ the changes JayD3V implemented: Create a file in the same directory as the barcode parser, and add the following script to it.
const BarCodeParser = require('./BarcodeParser.js');
let barcode = ']C101040123456789011715012910ABC123�39329784711�310300052539224711�42127649716';
console.log(BarCodeParser.parseBarcode(barcode));
Then execute the file using the node command.
The README.md document in the repository has much of the information I added here in it.
Here is what it looked like when I ran it:
you're using it on server-side (backend)
https://www.npmjs.com/package/gs1-barcode-parser?msclkid=bb2e3c05cf5111ecabd6ce6b8aeb965a
as its documentation says it is a library
it also says that in order to use gs1-barcode-parser you have to add it in your application (on client side / frontend) as below:
<script src="./src/BarcodeParser.js"></script>
then you can use single function provided by it (parseBarcode) as follow :
try {
var barcode = document.getElementById("barcode").value,
answer = parseBarcode(barcode);
// do something ...
} catch (e) {
alert(e);
}

Spawning Python process with Javascript

My goal is to run python code that the user would write on the website. I found out that spawn() could do it.
var process = spawn('python',["./script.py"] );
However, I do not want user to store their code in a file but rather i want their code to be executed directly. I want to take their code as a string and do something like this.
var process = spawn('python',pythonCodeString );
This method would obviously not work because spawn() takes file path as an argument. Are there other methods of executing user's python code with js?
P.S. I am making a website where one can edit an image using python code. For ex. user uploads an image and would want to change it to gray scale(all these transformation users can do with python)
You could just automatically create the .py file from the inputted python code/string and then subsequently call it with spawn() and delete it once it has been executed, much like a "temporary" script, so that the user doesn't need to store it manually inside a file.

Execute a file in global scope instead of returning exported object

In NodeJS I would like to simply execute a file and allow it to make modifications to the global namespace. I know that this is not the best practice, and if I was designing the project myself, I would make sure that each module exports a single variable.
I am converting a poorly structured SPA project joined by script tags into node, and I would like to do so incrementally.
Right now I have:
require('./three.js')
This is a version of threejs which simply fills a global variable named 'THREE' with the contents of the module. Since the execution of require implicitly creates a closure, a global variable is not created for me.
So what I'd like to do is just run an entire js file and allow it to create global variables.
Is there an elegant way to do this?
You are working on Single Page Application which use the node server to run. So why don't you try module.exports = so that you can see that under the name space you give.
So example
var THREE_74 = require('./three');
Now this THREE_74.HemispherLight()
you can access probably this what you doing.
And if you want to bring your application out of node than use same layout as present ( since you are converting the SPA application) and then create your index.html load the require.js file ( http://requirejs.org/docs/download.html ) into the script tag make all your file than call after this js file ( into those file do the require as you are doing now ).
then run single line server python -m SimpleHTTPServer and run on the browser simple :)
I was able to find this snippet. It isn't native in Node, but it works well as a provisional solution!
var fs = require('fs');
var vm = require('vm');
var includeInThisContext = function(path) {
var code = fs.readFileSync(path);
vm.runInThisContext(code, path);
}.bind(this);
includeInThisContext("<PATH_TO_FILE>");

How to obtain location of the code being executed in Nodejs

Trying to create a logger javascript class, that I add as a require() in other javascript files. One of the functions of this logger should be, that it writes to the console which script is currently running.
They way I thought it would execute , was that I have a path.basename(__Filename) function inside my logger, but how would I go around targeting the filename of the script executing the logger script?
There is no way to know which file the script itself is in as the browser loads all the scripts under the DOM while loading the page.
function xyz(){
console.log(arguments.callee.toString().match(/function ([^\(]+)/)[1]);
}
This should give you the name of the function that's being called as long as the function is declared in function xyz(){} format. In this case xyz.

Importing javascript file multiple times on same page

I have a javascript file called pendingAjaxCallsCounter.js with a variable "var pendingAjaxCalls" which is incremented/decremented when various methods in the js file are called.
Separately, I have created an automated testing app which checks that the pendingAjaxCalls has a value of 0 before interacting with any page. I'm wondering, if a given page, were to import the js file multiple times; multiple
statements, how would that affect the value of my variable "var pendingAjaxCalls"?
The script would be run each time it was included, but make sure that you don't redefine the pendingAjaxCalls variable each time. i.e. Check it's defined before declaring it with something like:
if(!pendingAjaxCalls)
var pendingAjaxCalls=0;
/* code happens here */
pendingAjaxCalls++;
Each time you include a script using a script tag, the browser will download the file and evaluate it. Each time you include a JavaScript file the contents will be evaluated.
If the actual call to the function that increments your variable is being inserted more than once, you could be incrememting it multiple times.
On the other hand, if only the function that increments it is being inserted multiple times (not the function call), then JavaScript will use the most recently defined version of this function. So it shouldn't be incremented extra times in that case.
In other words, if you insert the same function twice but only call it once, you don't have to worry about "both copies" of the function being called, since one copy effectively overwrites the other.

Categories