How to find where an application got installed in linux using nodejs - node.js

I installed a server on linux. The installation files gets installed under /opt/AppName/ while the service is under /etc/systemd/system/. I need to get the path of a folder 'cert' which is under /opt/AppName when the server starts. Now the process tries to look under current working directory or the root which obviously fails. How do I get the location where the install files are present?
Have tried:
const dircert = 'cert'
const certificateDirWin = path.resolve(`${process.cwd()}`, dircert)
and
const certificateDir = path.resolve(__dirname, dircert)
None of these work.
However if I hardcode
const certificateDirLin = path.resolve('/opt/AppName', dircert)
it works.
How do I get rid of the harcoded path.

Related

rootDirName returning wrong part of the path

I have a Gulpfile which runs in the 'theme' folder of my project.
C:\wamp\www\mywebsitename\wp-content\themes\mythemename\gulpfile.js
In the gulpfiule, need to get the local website URL, which is basically just the 'mywebsitename' part of this path.
I have historically used this code to get it successfully:
"var rootDirName = path.basename(__dirname, '../../../');"
However I recently re-installed Windows, Node and Gulp, and now that line of code returns 'mythemename' instead of 'mywebsitename', ignoring the '../../../' argument.
If I remove that argument, it stil returns 'mythemename'.
I'm guessing some newer version of Gulp, Node or something in Windows has changed how this method works. Please can anyone suggest why this no longer works, or if there is a better way to always go 3 levels up the file tree from the gulpfile.js directory?
Worked it out myself.
const path = require('path');
var rootDirPath = path.join(__dirname, '../../../');
var rootDirName = path.basename(rootDirPath);
var url = 'http://localhost/' + rootDirName;
This will allow you to get the website's URL on localhost in Gulp and do what you need to with it (in my case, using the Critical CSS tool to scan the website and inline all the header CSS).

How to read contents of a directory in linux on nodejs?

I am creating an application on nodejs that has to read contents of a folder in the install location. The installer creates the directory 'cert' at the install location.
My code is:
const dircert = './cert'
files = fs.readdirSync(dircert)
if (!files.length) {
***some code***
} else {
files.forEach(file => {
if (path.extname(file) == '.key') {
pathkey = path.resolve(dircert, file)
}
if (path.extname(file) == '.crt') {
pathcert = path.resolve(dircert, file)
}
})
This runs fine in windows but not in Linux. The installer is not able to read the contents. What do I need to change to ensure that it works in both? I am pretty new to linux.
The application is getting installed in ProgramFiles in windows but in /opt/AppName in linux. Please suggest.
Editing to add: So this cert folder is getting created under /opt/AppName/ in linux and under c:/ProgramFiles/company/App Name/ in Windows. While this code runs fine on windows, on linux this code tries to look for cert at root. How do I make sure it looks for the folder at the installed location which is /opt/AppName, and it should work on both the platforms.
It's unclear from your question how the files are being installed and how the code is being executed. Both of these matter in Linux. You can use the __dirname node variable with path.resolve() to get the directory of the current module. If cert is below the current module, you can use the following code to resolve the location:
const path = require('path');
const dircert = path.resolve(__dirname, 'cert');
If you're using ES Modules:
import path from 'path';
const dircert = path.resolve('cert').

How to access the base package form a node_module

I am looking to access a JSON config file that the user would place next to their package.json from a node_module package that I created. Is there a best approach to do this. I tried a relative import but that didn't really work and I am not sure how best to accomplish dynamic imports if the config file doesn't exist because I want to allow it to not exist as well.
Here is how I tried to handle dynamic imports though:
export const overrides = (function () {
try {
return require('../../../../../../overrides.json');
} catch (_err) {
return null;
}
})();
Also I tried fs but I get a browser config error I am not sure if that is something else. I should research but I didn't understand the docs around that.
using a library
This worked for me: find-package-json
Basically on any js file who needs the base, home or workspace path, do this:
var finder = require('find-package-json');
var path = require('path');
var f = finder(__dirname);
var rootDirectory = path.dirname(f.next().filename);
rootDirectory will be the location of the folder in which the main package.json exist.
If you want to optimize, get the appRootPath variable at the start of your app and store/propagate the variable to the hole nodejs system.
no libraries
Without any library, this worked for me:
console.log("root directory: "+require('path').resolve('./'));
This will get you the root directory of your nodejs app no matter if you are using npm run start or node foo/bar/index.js
More ways to get the root directory here:
Determine project root from a running node.js application
usage
If you achieve to obtain the root directory of your nodejs app and your file is at the package.json level, use this variable like this to locate any file at root level:
rootDirectory+"/overrides.json"

Working when run, but not when built

Im on macOS. I am creating a simple electron app. When I run the app with electron . everything works perfectly with no errors. Now that my app is finished, I wanted to build and distribute it. So I setup electron-builder and I got that to work just fine. However, when I run the MyApp.app in the build folder, I get an error saying:
Uncaught Error: ENOENT: no such file or directory, scandir './img/'
I call scandir here:
const fs = require('fs');
var files = [];
fs.readdirSync("./img/").forEach(file => {
files.push(file);
})
Why is this working when I run it with node, but is not working in the build? How can I fix this issue?
Why is this working when I run it with node, but is not working in the
build? How can I fix this issue?
It's difficult to tell without having more information about the whole app's structure, it may depend on how your code is actually called or required from the html file.
Anyway, using the __dirname global variable to build the directory path usually solves this kind of problem. Please try:
const fs = require('fs');
const path = require('path');
var files = [];
fs.readdirSync(path.join(__dirname, 'img')).forEach(file => {
files.push(file);
});

Setting Up Node.js App Directory

I'm completely new to using Node.js and even utilizing the command line, so this question may be extremely elementary, but I am unable to find a solution.
I am trying to set up an app directory using Node.js and NPM. For some reason, whenever I try to use the port:5000 I get a "Cannot GET/" error. My question is, why is my setup for my app directory not working?
I have installed connect and serve-static, and yet it will not retrieve files and listen on port 5000. I have created a server.js file in my user, kstach1. Here is the code I have within that file:
var connect = require('connect');
var serveStatic = require('serve-static');
var app = connect();
app.use(serveStatic('../angularjs'));
app.listen(5000);
So, I don't quite understand why this won't reference my folder of angularjs, where I want to store my app. I have tested it by adding a file within the folder called test.html, and entered localhost:5000/test.html, and still get the "Cannot GET/test.html" error.
I know that Node is working correctly because I can enter scripts into the command line and they give the correct output. I do this as a user (kstach1).
The only thing I can think of that I may be doing wrong, is where my files are located. I have the angularjs folder located in the root user folder on my Mac (kstach1), as well as the server.js file. Is this incorrect? If this is not the issue, is it because of where Node is installed (usr/local/bin/node)? My research to this point has led me to think that my problem could also be that I need to add the installation directory to my path. However, I don't want to mess with this unless I know that is the case.
Any help would be greatly appreciated.
I did a little research on the serve-static package and copied the code you provided.
My project folder is located at "C:\teststatic" and the folder with the static files is: "C:\angularjs", also using "text.html" that is located in the 'angularjs' folder.
When running the code you provided and going to localhost:5000 it indeed returns "Cannot GET/". This is most likely because there is no "/" file declared.
Going to localhost:5000/test.html works for me, so you could try setting a "/" like this:
app.use(serveStatic('../angularjs', {'index': ['test.html', 'index.html']}));
And see if that works for you. If not, you should double check directory names / locations.
EDIT:
From reading the comment you posted: try this instead:
app.use(serveStatic('angularjs'));
I suggest moving your angularjs folder up into your main project's directory in a public/ folder. Its a pretty standard convention to have all of your static assets in public/. You can then use the path module to automatically resolve your path, inserting this where you have '../angularjs': path.join(__dirname, 'public').
So, your code would look like this:
var connect = require('connect');
var serveStatic = require('serve-static');
var app = connect();
var path = require('path');
app.use(serveStatic(path.join(__dirname, 'public'));
app.listen(5000);
And, your directory structure would look like this:
server.js
public/
angularjs/
test.html
You should then be able to use localhost:5000/angularjs/test.html to view your test.html

Resources