Configure electron-builder to run powershell script - javascript

I have an installation file created by electron-builder and faced issue that can't find a way how to run powershell script after installation.
The idea is to make some changes in windows registry and set permission for application folder.
As far as I understand it should be configured in build section in package.json. In api I found that it is exist afterPack method, but I can't figure it out how to execute powershell file through it.
Thank you.

First, create an afterPack.js file, containing this code:
exports.default = async function () {
const { exec } = require('child_process');
const bat = exec('powershell "& ""path/to/powershell/file.ps1"""');
}
Edit the path to the .ps1 file accordingly. You may need to add a '.\' to the start of the path. The console readout will tell you if you do.
Next, edit your package.json file to include an afterPack parameter in your build settings, like so:
Now when you run your build script, it will run your .ps1 file.

Related

Uncaught TypeError: Cannot read properties of undefined (reading 'json_to_sheet')

I am getting this error and do not know what to do. I have not used node_modules before, so it would be nice with help.
my files:
i am using the test.js filecode:
const XLSX = fetch('xlsx')
// array of objects to save in Excel
let binary_univers = [{'name': 'Hi','value':1},{'name':'Bye','value':0}]
console.log(binary_univers)
let binaryWS = XLSX.utils.json_to_sheet(binary_univers);
// Create a new Workbook
var wb = XLSX.utils.book_new()
// Name your sheet
XLSX.utils.book_append_sheet(wb, binaryWS, 'Binary values')
// export your excel
XLSX.writeFile(wb, 'Binaire.xlsx');
What i am trying to do is to have data into xlsx, but for some reason it does not know the function "json_to_sheet".
please comment if you know how to fix it! I am also unsure on what Node.js is, so if that is related please explain to me.
Discord:
Abinesh🦞#6158
UPDATE:
I have done what you said, but i wont still work. DId i do something wrong? (look at the picture)
(i am using the test.js file)
you need to install xlss first to your project, open a terminal and go to you project path and install the xlss liberary
i.e
$ npm install xlsx
other ways to install
once installed, you can use this without any error
const xlsx = require('xlsx');
updated answer:
after looking into your package.json , it's clear it's not configured properly, so follow this stpes
Create an empty folder and open it in terminal.
type npm init -y on the empty folder, once done you should see a proper package.json
type npm install xlsx
create a new file and name is whatever you like (e.g myFile.js)
and paste you excel code there.
make an edit in package.json on the script key, like this
"scripts": {
"start": "myFile.js"
},
Now you run the code and should not see any error, command to run node .\myFile.js

require.resolve not finding file even though fs can

I'm having a problem with node.js require.resolve the method that makes no sense having with the test I'm running first.
So my Code
let checkPluginCanLoad = (pluginName, pluginFile) => {
return new Promise((res, rej) => {
// build the plugin's class files path
console.log(`looking for file at ${path}/${pluginName}/${pluginFile}`)
let req = `${path}/${pluginName}/${pluginFile}`
// check it exists blocking
let fileState = fs.existsSync(`${req}.js`);
if(fileState){
console.log(`File ${req}.js ${fileState?"exists.":"does not exist."}`);
// it exists try to load it
let plugin = require.resolve(`${req}`);
res(plugin);
}else{
// could not find or load the plugin
rej(`Plugin is invalid can't find or load class for ${pluginFile}`);
}
});
}
The vars are set to , path = "Plugins", pluginName = "TestPlugin", pluginFile = "TestPlugin";
My output is
Plugins from 'Plugins' have been loaded. index.js:36
looking for file at Plugins/TestPlugin/TestPlugin Plugins.js:133
File Plugins/TestPlugin/TestPlugin.js exists. Plugins.js:138 failed to
load plugin 'TestPlugin' with error 'Error: Cannot find module 'Plugins/TestPlugin/TestPlugin''
The final line
load plugin 'TestPlugin' ... comes from the system above this one catching the rejection.
So the file Exists according to FileSystem but the resolver can't find it.
I have tried prepending it with ../ before the path in case it's resolving from the file that is running it and not the application directory,
I have also tried prepending it with ./ in case it's running it from the application directory.
you need to add ./ to tell node that you are targeting local file.
let plugin = require.resolve(`./${req}`);
if you forgot node will search in steps described here
So this is a bug caused by symlinks on windows with junctioned directories,
So for my dev environment it junctions the directories from my Git Repository directory. but Node is running it through the junction directory but seeing the original directory.
E.G
Git repo is in D:\Projects\NodeAppRepo
then the dev environment is running inside D:\Project\NodeApp\
I have index.js, Core/, node_modules/ all running via a junction inside the NodeApp to the paths in the git repo.
so i'm running node index.js inside D:\Project\NodeApp\ wich is in turn loading D:\Project\NodeApp\Core\Core.js this then imports ./Plugins.js this is where the break happens because the path node has for plugins is not D:\Project\NodeApp\Core\Plugins.js it is D:\Projects\NodeAppRepo\Core\Plugin.js

SFTP-Nodejs create folder in remote location

I had used the following node module for sftp implementation.
https://www.npmjs.com/package/ftps
My target is to create a folder in the remote location and save my file. In the see the available session( http://lftp.yar.ru/lftp-man.html) in the documentation it shows mkdir as an option. But I have no idea how to use it. Kindly help me create a folder in remote location. I am new to server development and this confuses me. Or is it possible to create a folder?
It seems to be in the documentation but not in the actual source code index.js
You will have to use another libary.
Just adding the following lines to index.js of node modules worked.
FTP.prototype.mkdir = function (directory , mode) {
return this.raw('mkdir '+mode+' '+directory)
};
The function call in the program is as follows
ftps.mkdir(path,['-p']).cd(path).addFile(file);

aws-lambda Cannot find module

I keep getting this error in the aws-lambda console when uploading code from a zip file. I have tried uploading other zip files and they work correctly. The .js file is named "CreateThumbnail.js" in the zip file. I believe the handler is also named properly "CreateThumbnail.handler". the node_modules subdirectory is also setup. Anyone have any idea?
{
"errorMessage": "Cannot find module 'CreateThumbnail'",
"errorType": "Error",
"stackTrace": [
"Function.Module._resolveFilename (module.js:338:15)",
"Function.Module._load (module.js:280:25)",
"Module.require (module.js:364:17)",
"require (module.js:380:17)"
]
}
The way I was able to get this to work was:
Name the file exports.js
Name the handler, within the file, exports.handler
Set the handler in the lambda config to exports.handler
Zip up only the contents of the folder, not the folder itself (as mentioned above) and rename the zip file exports.zip
Ok, I did this myself, just make sure that you make the zip such that the .js file doesn't end up inside a folder, because AWS would unzip the file you upload and tries to find a .js file by the name of handler you gave, and if its inside a folder it won't help you.
One possible problem is if you upload the lambda as a zip file created via PowerShell Compress-Archive. Compress-Archive has a bug which causes AWS to extract the files into a flat tree (no subdirectories), with backslashes in filenames:
This exact error can show up if your zipped file(s) do not have world-wide read permission. (chmod -R ugo+r).
Check the file permissions before they are zipped. This is not emphasized enough unfortunately by AWS and it caused a lot of headaches for many.
If you are using AWS Lambda Layers you need to validate if your directory structure is on the needed structure for a layer:
For example for the moment.js node.js module you need the following structure:
aws-lambda-layer.zip
│ nodejs
│ nodejs/node_modules
â”” nodejs/node_modules/moment
So to create a layer zip file with the correct structure we can use the following command on the root of our project:
mkdir -p nodejs && cp -r node_modules nodejs/ && zip -r aws-lambda-layer.zip nodejs
Some library files might not have global Read so lambda will not be able to read to content and build the content.
Make sure all files in node_modules are readable before packaging:
chmod -R +r node_modules
Then zip and upload.
This is the instruction from https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html that I have followed and it works.
To update a Node.js function with dependencies
Open a command line terminal or shell. Ensure that the Node.js version in your local environment matches the Node.js version of your function.
Create a folder for the deployment package. The following steps assume that the folder is named my-function.
Install libraries in the node_modules directory using the npm install command.
npm install the_package_that_is_missing
Create a .zip file that contains the contents of your project folder. Use the r (recursive) option to ensure that zip compresses the subfolders.
zip -r function.zip .
Upload the package using the update-function-code command.
aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip
Now your function is ready to run!
I had this problem on a custom module I had built that was in the node_modules dir. Everything ran fine in testing on my Win10 machine, but when uploaded I kept getting that same "Cannot find module 'modulename'" error.
It turns out that I had a mismatch; here's the package.json line from the module that couldn't be found:
"main": "./build/modulename.js",
and here's the actual filename:
Modulename.js
Case-sensitive; Windows isn't, linux (and thus AWS) is.
This is unrelated but google brought me here, so:
AWS will give you an error:
Unable to import module '<myfile>': Error
What was really happening for me, was that was requiring an unexisting JS file. The error is a bit misleading.
I ran into this same scenario, solved it by using these specific steps to create a Layer, then hook that up to the Lambda function.
make a new empty directory:
mkdir newdir && cd newdir
install whatever npm things:
npm install --save xyz
make a directory skeleton that matches the expected Lambda structure for Node14 (there's a different structure for Node12, or various other languages; see https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html?icmpid=docs_lambda_help):
mkdir -p nodejs/node14
copy the "node_modules" directory into that newly made directory skeleton:
cp -R node_modules nodejs/node14
zip the whole thing up (name it whatever you want):
zip -r custom-drivers-node14.zip nodejs
from there, go to AWS console, Lambda, then "Layers" and create a new layer. In the dialog, upload your .zip file ("custom-drivers-node14.zip").
finally, edit your Lambda function in AWS console, and add a new Layer – the interface might change, but as of now, this is under the main screen for a single function, then scroll way down to the bottom. Follow the "Add a layer" flow, choose the Layer you made, and then try your code.
One final note, this code structure worked:
const xyz = require('xyz');
exports.handler = async (event) => {
xyz.doSomething();
}
AWS Lambda uses the name of the file and the name of the handler function, so if you defined your handler like this: exports.myHandler = function(event, context) in a file named index.js, your handler is index.myHandler.
This turned out to be a simple one for me.
I was getting, cannot create index. in my case, my main lambda file with the exports.handler in had to be called index.js
Try calling your main file CreateThumbnail.js
The tutorial tells you to include the following items in your zip file:
CreateThumbnail.js
/node_modules/gm
/node_modules/async
What it fails to consider is that there are dependencies of the two packages (gm, async) that also need to be part of the package.
So here's what you have to do:
Change directory to node_modules folder in your project folder, and run the command 'npm install gm async'. This will install gm, async and all their dependencies in this folder.
Now package the 'CreateThumbnail.js' file and the complete 'node_modules' folder into a zip file and upload it. It should work now.
So your complete package should look something like this:
CreateThumbnail.js
/node_modules/.bin
/node_modules/array-parallel
/node_modules/array-series
/node_modules/async
/node_modules/cross-spawn
/node_modules/debug
/node_modules/gm
/node_modules/isexe
/node_modules/lodash
/node_modules/lru-cache
/node_modules/ms
/node_modules/pseudomap
/node_modules/which
/node_modules/yallist
File Name:
app.js
Lambda Function in "app.js":
exports.handler = function(event, context)...
Lambda Handler on Amazon Console:
app.handler ({app}.js + exports.{handler} = app.handler)
When you unzip the folder, you should see:
app.js
node_modules

Where to place JS files for NodeJS to see them

I've just installed NodeJS on my Mac, and i got it working in the terminal, using inline scripting like "console.log('Hello world'); works fine.
But where do i place JS files for NodeJS to find them? Can i specify the root folder NodeJS to look for file in?
I followed this guide: http://nodeguide.com/beginner.html#learning-javascript
but i cannot get any of the samlpe to work where i reference a script file.
You put them in whatever folder you want. It is common practice to put each application in a different folder.
Then you run node.js like this:
node /path/to/file.js
Or like this:
cd /path/to/
node file.js
Where file.js might look something like this:
console.log('hello world');
You'll have to navigate to the correct folder "manually", in the Node Command Line Interface (CLI).
If you need to change drives, type the drive letter and a colon to switch to that drive, like so;
C:> (<- this is the line prompt, yeah? Just add this after it -> D:
That changes the drive. Now write cd (CD = "Change Directory") and the name of the direcotry you want to go to the directory your stuff is in:
D:> (<- the new prompt. Write something like this after it: ->) cd myprosject\subfoldername
D:\myproject\subfoldername> (<- your new line prompt - if "myproject\subfoldername" exists)
now ask node to execute your script (that is stored in myproject\subfoldername, like so;
D:\myproject\subfoldername> node helloworld.js
Remember to write "node" first - otherwise the command won't go to node, but to the OS, which will probably just open up the js file in a text editior instead of running the goodies inside.
It is very easy.. Go to your command line. navigate to the file location..
then simply run the node helloworld.
I'm not sure I understand. it doesnt 'look' anywhere for your .js files you point at them when you run node. Like so, on the command line:
node mynodeapp.js
If you're meaning where does it look for your .js files as modules, when requirign them, like so:
var mymodule = require("mymodule");
Then it will look inside a folder names node_modules. But I'm sure you're looking for my first example above.

Categories

Resources