Importing customized module into renderer.js in Electron app - node.js

I have a customized module that carries some functions that I would like to use in renderer.js. I tried the following ways of importing but it does not work (in fact, it causes some of the other functions in renderer.js to not execute as well.
const supp = require('./supp.js')
const supp = require('./supp')
const supp = require('supp.js')
const supp = require(path.join(__dirname, '/supp.js')
import 'supp'
supp.js sits in the same folder level as renderer.js and main.js. If someone could advise? Thanks.
Update: below is all the code in file supp.js
const pinOneInGrp = (itemID, grpName, itemColor, grpColor) => {
let item = document.getElementById(itemID);
let grpItems = document.getElementsByClassName(grpName);
for(var i = 0; i < grpItems.length;i++) {
grpItems[i].style.background-color = grpColor
}
item.style.background-color = itemColor;
}
module.exports = {
pinOneInGrp
}
If one of the import or require lines above is included at the top of renderer.js, none of the subsequent actions in renderer.js is executed. For example, there is a ipc.send() and ipc.on() action right after the import / require line. These two do not send (and hence, receive back) from the main.js.

The code you've posted contains a typo. The error it's throwing (which you most probably can't see) is a SyntaxError, because you cannot subtract color (which is undefined) from grpItems[i].style.background and then assign to it. Thus, you simply have to correct your for-loo from
for (var i = 0; i < grpItems.length; i++) {
grpItems[i].style.background-color = grpColor;
}
to
for (var i = 0; i < grpItems.length; i++) {
grpItems[i].style.backgroundColor = grpColor;
}
(And the same goes for the style assignment right below the for-loop!)
Note that all CSS properties which are spelt with a hyphen when in a stylesheet must use camelCase as they otherwise would denote a subtraction, which is causing your problems. Also, this behaviour is explained in Mozilla's Developer Network Web API reference, specifically under "Setting styles".

Related

TS/Node.js: Getting the absolute path of the class instance rather than the class itself

Is there a way to get the path (__dirname) of the file where an instance of a class was made without passing that into the constructor?
For example,
// src/classes/A.ts
export class A {
private instanceDirname: string;
constructor() {
this.instanceDirname = ??
}
}
// src/index.ts
import { A } from "./classes/A"
const a = new A();
// a.instanceDirname === __dirname ✓
I tried callsite, it worked but I had to do some regex that I'm not happy with to get what I need, I also tried a module called caller-callsite, but that ended up returning the module path, not the path of the file where the instance was made.
Is there a workaround for this?
I would have callers pass in the location information. Sniffing this stuff seems like a code smell to me (pardon the pun). ;-)
But you can do it, by using regular expressions on the V8 call stack from an Error instance, but it still involves doing regular expressions (which you didn't like with callsite), though it's doing them on V8's own stacks, which aren't likely to change in a breaking way (and certainly won't except when you do upgrades of Node.js, so it's easy to test). See comments:
// A regular expression to look for lines in this file (A.ts / A.js)
const rexThisFile = /\bA\.[tj]s:/i;
// Your class
export class A {
constructor() {
// Get a stack trace, break into lines -- this is V8, we can rely on the format
const stackLines = (new Error().stack).split(/\r\n|\r|\n/);
// Find the first line that doesn't reference this file
const line = stackLines.find((line, index) => index > 0 && !rexThisFile.test(line));
if (line) {
// Found it, extract the directory from it
const instanceOfDirName = line.replace(/^\s*at\s*/, "")
.replace(/\w+\.[tj]s[:\d]+$/, "")
.replace(/^file:\/\//, "");
console.log(`instanceOfDirName = "${instanceOfDirName}"`);
}
}
}
Those three replaces can be combined:
const instanceOfDirName = line.replace(/(?:^\s*at\s*(?:file:\/\/)?)|(?:\w+\.[tj]s[:\d]+$)/g, "");
...but I left them separate for clarity; not going to make any performance difference to care about.

How to get known Windows folder path with Node

I need to access per-machine configuration data in my Node application running on Windows. I've found this documentation for how to find the location:
Where Should I Store my Data and Configuration Files if I Target Multiple OS Versions?
So, in my case, I would like to get the path for CSIDL_COMMON_APPDATA (or FOLDERID_ProgramData). However, the examples are all in C, and I would prefer to not have to write a C extension for this.
Is there any other way to access these paths from Node, or should I just hardcode them?
After doing a bit of research, I've found that it's possible to call the relevant Windows API proc. (SHGetKnownFolderPath) to get these folder locations, see docs at: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762188(v=vs.85).aspx.
We call the APi using the FFI npm module: https://www.npmjs.com/package/ffi.
It is possible to find the GUIDs for any known folder here:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd378457(v=vs.85).aspx
Here is a script that finds the location of several common folders,
some of the code is a little hacky, but is easily cleaned up.
const ffi = require('ffi');
const ref = require('ref');
const shell32 = new ffi.Library('Shell32', {
SHGetKnownFolderPath: ['int', [ ref.refType('void'), 'int', ref.refType('void'), ref.refType(ref.refType("char"))]]
});
function parseGUID(guidStr) {
var fields = guidStr.split('-');
var a1 = [];
for(var i = 0; i < fields.length; i++) {
var a2 = [...Buffer.from(fields[i], 'hex')];
if (i < 3) a2 = a2.reverse();
a1 = a1.concat(a2);
}
return new Buffer(a1);
}
function getWindowsKnownFolderPath(pathGUID) {
let guidPtr = parseGUID(pathGUID);
guidPtr.type = ref.types.void;
let pathPtr = ref.alloc(ref.refType(ref.refType("void")));
let status = shell32.SHGetKnownFolderPath(guidPtr, 0, ref.NULL, pathPtr);
if (status !== 0) {
return "Error occurred getting path: " + status;
}
let pathStr = ref.readPointer(pathPtr, 0, 200);
return pathStr.toString('ucs2').substring(0, (pathStr.indexOf('\0\0') + 1)/2);
}
// See this link for a complete list: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378457(v=vs.85).aspx
const WindowsKnownFolders = {
ProgramData: "62AB5D82-FDC1-4DC3-A9DD-070D1D495D97",
Windows: "F38BF404-1D43-42F2-9305-67DE0B28FC23",
ProgramFiles: "905E63B6-C1BF-494E-B29C-65B732D3D21A",
Documents: "FDD39AD0-238F-46AF-ADB4-6C85480369C7"
}
// Enumerate common folders.
for(let [k,v] of Object.entries(WindowsKnownFolders)) {
console.log(`${k}: `, getWindowsKnownFolderPath(v));
}

Making ESLint work for files which are loaded by others

I have a set of scripts in which one loads another script file and uses the functions defined in it.
For example, let's say I have main.js script with the following source
load("helper.js");
var stdin = new java.io.BufferedReader( new java.io.InputStreamReader(java.lang.System['in']) );
function readline() {
var line = stdin.readLine();
return line;
}
var N = parseInt(readline());
for(var i = 0; i< N; i++)
{
print("fd630b881935b5d43180ff301525488a");
var num = parseInt(readline());
var ans = perfectNumberCheck(num);
print(ans);
print("dc29e6fa38016b00627b6e52956f3c64");
}
I have another script file, helper.js which has the following source
function perfectNumberCheck(num) {
if(num == 1)
{
return 0;
}
var halfNum = (num/2) + 1;
var sum = 0;
var retVal = 0;
for(var i=1 ; i < halfNum; i++){
if(num % i === 0){
sum = sum + i;
}
}
if(sum == num){
retVal = 1;
}
else {
retVal = 0;
}
return retVal;
}
As it can be seen, main.js uses the function perfectNumberCheck. Now, when I run ESLint on both the files using eslint main.js helper.js or by using eslint *.js, I get the no-unused-vars error 'perfectNumberCheck' is defined but never used even though it is being used in main.js.
I want to keep this error in the configuration but don't want ESLint to show it in such cases.
Is there a way to make ESLint resolve these dependencies without writing the entire code in a single script file?
You can add a comment like /* exported perfectNumberCheck */ to helper.js to tell no-unused-vars that the function is used elsewhere outside that file:
/* exported perfectNumberCheck */
function perfectNumberCheck() {
// ...
}
By itself, ESLint lints each file in isolation, so it will not resolve identifiers defined in other files. The /* exported ... */ comment and globals allow you to inform ESLint of dependencies in other files.
Since exported comments are intended to be used to indicate names that are used elsewhere by being present in the global scope, they have no effect when the file's source in not in the global scope. Specifically, quoting the docs:
Note that /* exported */ has no effect for any of the following:
when the environment is node or commonjs
when parserOptions.sourceType is module
when ecmaFeatures.globalReturn is true

Can I load multiple files with one require statement?

maybe this question is a little silly, but is it possible to load multiple .js files with one require statement? like this:
var mylib = require('./lib/mylibfiles');
and use:
mylib.foo(); //return "hello from one"
mylib.bar(): //return "hello from two"
And in the folder mylibfiles will have two files:
One.js
exports.foo= function(){return "hello from one";}
Two.js
exports.bar= function(){return "hello from two";}
I was thinking to put a package.json in the folder that say to load all the files, but I don't know how. Other aproach that I was thinking is to have a index.js that exports everything again but I will be duplicating work.
Thanks!!
P.D: I'm working with nodejs v0.611 on a windows 7 machine
First of all using require does not duplicate anything. It loads the module and it caches it, so calling require again will get it from memory (thus you can modify module at fly without interacting with its source code - this is sometimes desirable, for example when you want to store db connection inside module).
Also package.json does not load anything and does not interact with your app at all. It is only used for npm.
Now you cannot require multiple modules at once. For example what will happen if both One.js and Two.js have defined function with the same name?? There are more problems.
But what you can do, is to write additional file, say modules.js with the following content
module.exports = {
one : require('./one.js'),
two : require('./two.js'),
/* some other modules you want */
}
and then you can simply use
var modules = require('./modules.js');
modules.one.foo();
modules.two.bar();
I have a snippet of code that requires more than one module, but it doesn't clump them together as your post suggests. However, that can be overcome with a trick that I found.
function requireMany () {
return Array.prototype.slice.call(arguments).map(function (value) {
try {
return require(value)
}
catch (event) {
return console.log(event)
}
})
}
And you use it as such
requireMany("fs", "socket.io", "path")
Which will return
[ fs {}, socketio {}, path {} ]
If a module is not found, an error will be sent to the console. It won't break the programme. The error will be shown in the array as undefined. The array will not be shorter because one of the modules failed to load.
Then you can bind those each of those array elements to a variable name, like so:
var [fs, socketio, path] = requireMany("fs", "socket.io", "path")
It essentially works like an object, but assigns the keys and their values to the global namespace. So, in your case, you could do:
var [foo, bar] = requireMany("./foo.js", "./bar.js")
foo() //return "hello from one"
bar() //return "hello from two"
And if you do want it to break the programme on error, just use this modified version, which is smaller
function requireMany () {
return Array.prototype.slice.call(arguments).map(require)
}
Yes, you may require a folder as a module, according to the node docs. Let's say you want to require() a folder called ./mypack/.
Inside ./mypack/, create a package.json file with the name of the folder and a main javascript file with the same name, inside a ./lib/ directory.
{
"name" : "mypack",
"main" : "./lib/mypack.js"
}
Now you can use require('./mypack') and node will load ./mypack/lib/mypack.js.
However if you do not include this package.json file, it may still work. Without the file, node will attempt to load ./mypack/index.js, or if that's not there, ./mypack/index.node.
My understanding is that this could be beneficial if you have split your program into many javascript files but do not want to concatenate them for deployment.
You can use destructuring assignment to map an array of exported modules from require statements in one line:
const requires = (...modules) => modules.map(module => require(module));
const [fs, path] = requires('fs', 'path');
I was doing something similar to what #freakish suggests in his answer with a project where I've a list of test scripts that are pulled into a Puppeteer + Jest testing setup. My test files follow the naming convention testname1.js - testnameN.js and I was able use a generator function to require N number of files from the particular directory with the approach below:
const fs = require('fs');
const path = require('path');
module.exports = class FilesInDirectory {
constructor(directory) {
this.fid = fs.readdirSync(path.resolve(directory));
this.requiredFiles = (this.fid.map((fileId) => {
let resolvedPath = path.resolve(directory, fileId);
return require(resolvedPath);
})).filter(file => !!file);
}
printRetrievedFiles() {
console.log(this.requiredFiles);
}
nextFileGenerator() {
const parent = this;
const fidLength = parent.requiredFiles.length;
function* iterate(index) {
while (index < fidLength) {
yield parent.requiredFiles[index++];
}
}
return iterate(0);
}
}
Then use like so:
//Use in test
const FilesInDirectory = require('./utilities/getfilesindirectory');
const StepsCollection = new FilesInDirectory('./test-steps');
const StepsGenerator = StepsCollection.nextFileGenerator();
//Assuming we're in an async function
await StepsGenerator.next().value.FUNCTION_REQUIRED_FROM_FILE(someArg);

Make a script work nice with the browser and node (npm)

I have a javascript lib, basically this is how it is structured so far:
var Ns = (function(){
var that = {};
// add stuff to 'that'
return that;
})();
//use Ns.foo() and Ns.bar()
The thing is that now, I wanted the same lib to be available with node and npm. So far this is what I could come up with:
this.Ns = (function(){ //same as previous snippet })()
//use Ns.foo() and Ns.bar()
The problem is that, while this works in the browser, in node I need to do this:
var Ns = require('ns').Ns
Problem: I'd love to be able to do var Ns = require('ns') but in order to do that I have to export this.foo and this.bar which will break the browser inclusion. Ideas?
// create local scope.
(function () {
var myModule = ...
// check for node module loader
if (typeof module !== "undefined" && typeof require !== "undefined") {
module.exports = myModule;
} else {
window["name"] = myModule;
}
})();
Creating a scope is probably the best route to go (so you don't have name collision issues), but an easier way to do this, by polluting the global scope, looks like this:
instead of
var x = require('x');
write
var x = (typeof require !== "undefined") ? require('x') : window;
and similarly, before added to exports, check if that object exists:
if (typeof exports !== "undefined)
exports.my_func = my_func;
The consequences of this, though, is that in the browser version everything gets dumped into global scope. Also, it assumes that the browser version loads the necessary scripts into the page. Easy to get working on a small scale... but I'm guessing it won't scale well.

Resources