How to run executable file from packaged Electron app - node.js

I am building an app with Electron in which there are some executables which run just fine when running npm start from terminal using the child-process in Javascript. However when packaging it with electron-builder my app just cannot find the executables. I have read many related posts and none answer my question.
The solution here https://github.com/sindresorhus/fix-path does not resolve my issue.
Here is my code
function updateCourses(platform){
const fixPath = require('fix-path');
alert(process.env.PATH);
fixPath(); //This is the package but does not resolve my issue
alert(process.env.PATH);
const path=require('path');
var fs = require("fs");
var mysql=require("mysql");
// /Applications/mooc-platform.app/
alert(__dirname);
const { exec } = require('child_process');
var run="./../../Users/thanasis/Desktop/mooc-platform\ Mac/scrape_"+String(platform);
exec(run,(error, stdout, stderr) => {
if (error) {
alert(`exec error: ${error}`);
alert(`Something wrong happened: ${stdout}`);
alert(`stderr: ${stderr}`);
return;
}
else{
alert(platform+" courses downloaded");
alert("Updating database");
var con=mysql.createConnection({
host: "localhost",
user: "root",
password: "simple1234",
database: "moocs"
});
var v=false;
con.connect(function(err){
if(err) throw err;
console.log("Connected!");
platform=String(platform);
var num = fs.readFileSync("../../Users/thanasis/Desktop/mooc-platform\ Mac/courses/"+platform+"/numofcourses.txt");
num=parseInt(num,10);
let plat=platform;
for(i=0; i<num; i++){
pth="../../Users/thanasis/Desktop/mooc-platform\ Mac/courses/"+platform+"/course"+i.toString()+".json";
var content = fs.readFileSync(pth);
var object = JSON.parse(content);
String.prototype.setCharAt = function(index,chr) {
if(index > this.length-1) return str;
return this.substr(0,index) + chr + this.substr(index+1);
}
var ti=String(object.title);
ti=ti.replace(/'/g,'i');
sql="INSERT INTO courses (name) VALUES('"+ti+"') ON DUPLICATE KEY UPDATE hits=0";
con.query(sql,function(err,result){
if(err) throw err;
console.log(result);
});
// con.query('DELETE FROM courses',function(err,result){
// if(err) throw(err);
// console.log(result);
// });
}
v=true;
con.end(function(err,result){
if(err) throw err;
if(!alert("Updated")){
window.location.href="load_courses.html";
}
});
});
}
});
}
Optimally this would run from the applications folder (in Macos) with no issue.
Any help would be greatly appreciated.

Assuming you are packaging your app as asar:
All your paths are relative to your file. So the moment this file changes its location the path won't work anymore.
Packing with asar changes
C:\myApp\scripts\main.js
to
C:\myApp\resources\myAppName.asar\scripts\main.js
so your files cannot be found from there.
There are a couple of options. For example:
Putting all of your executables and text files inside the asar.
Upside: you can distribute them with your app. Downside: App might
get big and this will not work with all executable files, as some may
need dependencies on their own.
Determine somehow an absolute path on the current machine (I have no
idea of macOS. On Windows I read the registry and extract the path I
need from there.)
Provide different paths if packed or not via e.g.
electron-is-running-in-asarpackage.

Related

How to set parameters to zip a folder in nodejs

I want zip a folder which contains few files. I am using zip-folder and 7zip-min modules they are working fine. But, I would like to add some parameters to it, like compression level and directory size and so on.
If it is not possible with this module, Can anyone provide other suggestions?
Here is my code :
Example 1-
const zipFolder = require('zip-folder');
zipFolder('./folder', './compressed.zip', function(err) {
if(err) {
console.log('something went wrong!', err);
} else {
console.log('done with compressing');
}
});
Example 2-
const _7z = require('7zip-min');
let pack = _7z.pack('./folder', './compressed.7z', err => {
console.log('I am done with compressing')
});

Need to read file from path to start cluster in nodejs

I am making a small project in which I need to start a cluster from the server file and that file I need to get from the commander cli argument.
program.start is to get the file name.
let filePath = fs.readFile(process.cwd() + "\\"+`${program.start}`, function(err, data)
{
if(err)
console.log(err)
else
console.log("completed");
});
if(cluster.isMaster){
const cpus = os.cpus().length;
console.log('Forking for ${cpus} CPUs');
for (let i = 0; i<cpus;i++){
cluster.fork();
}
}
else{
require(filePath);
}
AssertionError [ERR_ASSERTION]: missing path
I am stuck need help in this.

fs.createWriteStream, no such file or directory, open Nodejs

I want to save files that I am getting from another server on my server but the problem is when I am calling createWriteStream it giving me the error :
no such file or directory, open
E:\pathtoproject\myproject\public\profile_14454.jpg
Here is my code which is in E:\pathtoproject\myproject\modules\dowload.js :
request.head(infos.profile_pic, function(err, res, body) {
const completeFileName = '../public/profile_14454.' + res.headers['content-type'].split('/')[1];
var imageStream = fs.createWriteStream(completeFileName);
imageStream.on('open', function(fd) {
console.log("File open");
request(infos.profile_pic).pipe(imageStream).on('close', function(body) {
consoleLog('Profile pic saved');
console.log('This is the content of body');
console.log(body);
connection.query('UPDATE user set photo=? where id=?', [completeFileName, lastID], function(err, result, fields) {
if (err) {
consoleLog('Error while update the profile pic');
}
});
})
});
});
When I removed the directory ../public/ and leave only the name of the file
profile_14454.' + res.headers['content-type'].split('/')[1] , it worked but the file was saved in the root directory of the project (E:\pathtoproject\myproject\).
What's wrong in what I am doing? How can I have the file saved under public directory?
I am using nodeJS 8.9.4
I tried with my small code .
var fs = require("fs");
var data = 'Simply Easy Learning';
// Create a writable stream
var writerStream = fs.createWriteStream('./airo/output.txt');
// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');
// Mark the end of file
writerStream.end();
// Handle stream events --> finish, and error
writerStream.on('finish', function() {
console.log("Write completed.");
});
writerStream.on('error', function(err){
console.log(err.stack);
});
console.log("Program Ended");
My code is in this path E:\syed ayesha\nodejs\nodejs now I want to store my file in airo folder which is in this path. So I used one dot for storing. Hope this helps.

Read directory path from database/config and expose as static HTTP path (nodejs express)

I am using nodejs and express for my server side development. I need to expose repository as static path. This repository path is not hard coded and being stored in the database. I have method to read the config from database. This works well when I use other places except app.js. Following are my sample code.
Code to read config key from database and expose as static HTTP:
// for configuration
var AppUtilities = require('./server/utilities/AppUtilities');
app.configure(function() {
// set up our express application. Only showing the code related to static HTTP
app.use('/files', express.static(AppUtilities.appConfig.filesRepositoryPath)); //Expose repository as static content
});
app.listen(port);
AppUtilities.js
var documentOperationModule = require('./../persistence/DocumentOperation');
var constants = require("./../utilities/Constants");
//load application config from database and export as module.
documentOperationModule.getAllDocuments(constants.APPLICATION_CONFIG_COLLECTION, function(err, result) {
if (!err) {
console.log("loaded value from app config collection");
exports.appConfig = result[0];
} else {
//throw error
return new Error("Unable to load app config data error >> " + err);
}
});
I am getting following error when I tried to start nodejs.
TypeError: Cannot read property 'filesRepositoryPath' of undefined
I am new to nodejs. Please help and let me know in case I am not able to clarify my query.
The problem is that the getAllDocuments() function call is asynchronous and so it does not complete until some time after you require() AppUtilities.js.
The solution is to pass in a callback instead, something like:
// AppUtilities.js
var documentOperationModule = require('./../persistence/DocumentOperation');
var constants = require("./../utilities/Constants");
exports.loadAppConfig = function(cb) {
documentOperationModule.getAllDocuments(constants.APPLICATION_CONFIG_COLLECTION, function(err, result) {
if (!err) {
console.log("loaded value from app config collection");
exports.appConfig = result[0];
cb();
} else
cb(new Error("Unable to load app config data error >> " + err));
});
};
// Main entry point
var AppUtilities = require('./server/utilities/AppUtilities');
AppUtilities.loadAppConfig(main);
function main(err) {
if (err)
throw err;
app.configure(function() {
app.use('/files', express.static(AppUtilities.appConfig.filesRepositoryPath));
});
app.listen(port);
}

How to write file if parent folder doesn't exist?

I need to write file to the following path:
fs.writeFile('/folder1/folder2/file.txt', 'content', function () {…});
But '/folder1/folder2' path may not exists. So I get the following error:
message=ENOENT, open /folder1/folder2/file.txt
How can I write content to that path?
As of Node v10, this is built into the fs.mkdir function, which we can use in combination with path.dirname:
var fs = require('fs');
var getDirName = require('path').dirname;
function writeFile(path, contents, cb) {
fs.mkdir(getDirName(path), { recursive: true}, function (err) {
if (err) return cb(err);
fs.writeFile(path, contents, cb);
});
}
For older versions, you can use mkdirp:
var mkdirp = require('mkdirp');
var fs = require('fs');
var getDirName = require('path').dirname;
function writeFile(path, contents, cb) {
mkdirp(getDirName(path), function (err) {
if (err) return cb(err);
fs.writeFile(path, contents, cb);
});
}
If the whole path already exists, mkdirp is a noop. Otherwise it creates all missing directories for you.
This module does what you want: https://npmjs.org/package/writefile . Got it when googling for "writefile mkdirp". This module returns a promise instead of taking a callback, so be sure to read some introduction to promises first. It might actually complicate things for you.
The function I gave works in any case.
I find that the easiest way to do this is to use the outputFile() method from the fs-extra module.
Almost the same as writeFile (i.e. it overwrites), except that if the parent directory does not exist, it's created. options are what you'd pass to fs.writeFile().
Example:
var fs = require('fs-extra');
var file = '/tmp/this/path/does/not/exist/file.txt'
fs.outputFile(file, 'hello!', function (err) {
console.log(err); // => null
fs.readFile(file, 'utf8', function (err, data) {
console.log(data); // => hello!
});
});
It also has promise support out of the box these days!.
Edit
NodeJS version 10.12.0 has added a native support for both mkdir and mkdirSync to create the parent director recursively with recursive: true option as the following:
fs.mkdirSync(targetDir, { recursive: true });
And if you prefer fs Promises API, you can write
fs.promises.mkdir(targetDir, { recursive: true });
Original Answer
Create the parent directories recursively if they do not exist! (Zero dependencies)
const fs = require('fs');
const path = require('path');
function mkDirByPathSync(targetDir, { isRelativeToScript = false } = {}) {
const sep = path.sep;
const initDir = path.isAbsolute(targetDir) ? sep : '';
const baseDir = isRelativeToScript ? __dirname : '.';
return targetDir.split(sep).reduce((parentDir, childDir) => {
const curDir = path.resolve(baseDir, parentDir, childDir);
try {
fs.mkdirSync(curDir);
} catch (err) {
if (err.code === 'EEXIST') { // curDir already exists!
return curDir;
}
// To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows.
if (err.code === 'ENOENT') { // Throw the original parentDir error on curDir `ENOENT` failure.
throw new Error(`EACCES: permission denied, mkdir '${parentDir}'`);
}
const caughtErr = ['EACCES', 'EPERM', 'EISDIR'].indexOf(err.code) > -1;
if (!caughtErr || caughtErr && curDir === path.resolve(targetDir)) {
throw err; // Throw if it's just the last created dir.
}
}
return curDir;
}, initDir);
}
Usage
// Default, make directories relative to current working directory.
mkDirByPathSync('path/to/dir');
// Make directories relative to the current script.
mkDirByPathSync('path/to/dir', {isRelativeToScript: true});
// Make directories with an absolute path.
mkDirByPathSync('/path/to/dir');
Demo
Try It!
Explanations
[UPDATE] This solution handles platform-specific errors like EISDIR for Mac and EPERM and EACCES for Windows.
This solution handles both relative and absolute paths.
In the case of relative paths, target directories will be created (resolved) in the current working directory. To Resolve them relative to the current script dir, pass {isRelativeToScript: true}.
Using path.sep and path.resolve(), not just / concatenation, to avoid cross-platform issues.
Using fs.mkdirSync and handling the error with try/catch if thrown to handle race conditions: another process may add the file between the calls to fs.existsSync() and fs.mkdirSync() and causes an exception.
The other way to achieve that could be checking if a file exists then creating it, I.e, if (!fs.existsSync(curDir) fs.mkdirSync(curDir);. But this is an anti-pattern that leaves the code vulnerable to race conditions.
Requires Node v6 and newer to support destructuring. (If you have problems implementing this solution with old Node versions, just leave me a comment)
Perhaps most simply, you can just use the fs-path npm module.
Your code would then look like:
var fsPath = require('fs-path');
fsPath.writeFile('/folder1/folder2/file.txt', 'content', function(err){
if(err) {
throw err;
} else {
console.log('wrote a file like DaVinci drew machines');
}
});
With node-fs-extra you can do it easily.
Install it
npm install --save fs-extra
Then use the outputFile method instead of writeFileSync
const fs = require('fs-extra');
fs.outputFile('tmp/test.txt', 'Hey there!', err => {
if(err) {
console.log(err);
} else {
console.log('The file was saved!');
}
})
You can use
fs.stat('/folder1/folder2', function(err, stats){ ... });
stats is a fs.Stats type of object, you may check stats.isDirectory(). Depending on the examination of err and stats you can do something, fs.mkdir( ... ) or throw an error.
Reference
Update: Fixed the commas in the code.
Here's my custom function to recursively create directories (with no external dependencies):
var fs = require('fs');
var path = require('path');
var myMkdirSync = function(dir){
if (fs.existsSync(dir)){
return
}
try{
fs.mkdirSync(dir)
}catch(err){
if(err.code == 'ENOENT'){
myMkdirSync(path.dirname(dir)) //create parent dir
myMkdirSync(dir) //create dir
}
}
}
myMkdirSync(path.dirname(filePath));
var file = fs.createWriteStream(filePath);
Here is my function which works in Node 10.12.0. Hope this will help.
const fs = require('fs');
function(dir,filename,content){
fs.promises.mkdir(dir, { recursive: true }).catch(error => { console.error('caught exception : ', error.message); });
fs.writeFile(dir+filename, content, function (err) {
if (err) throw err;
console.info('file saved!');
});
}
Here's part of Myrne Stol's answer broken out as a separate answer:
This module does what you want: https://npmjs.org/package/writefile .
Got it when googling for "writefile mkdirp". This module returns a
promise instead of taking a callback, so be sure to read some
introduction to promises first. It might actually complicate things
for you.
let name = "./new_folder/" + file_name + ".png";
await driver.takeScreenshot().then(
function(image, err) {
require('mkdirp')(require('path').dirname(name), (err) => {
require('fs').writeFile(name, image, 'base64', function(err) {
console.log(err);
});
});
}
);
In Windows you can use this code:
try {
fs.writeFileSync( './/..//..//filename.txt' , 'the text to write in the file', 'utf-8' );
}
catch(e){
console.log(" catch XXXXXXXXX ");
}
This code in windows create file in 2 folder above the current folder.
but I Can't create file in C:\ Directly

Resources