Node.js - get directory of routes.js - javascript

I have my server.js file at let's say directory: /dir1
I start the server with node server.js.
I have my file routes.js in directory /dir1/app/.
I want to get the directory of the server.js file.
I am not too sure how to do this. I can place code that tells me the location of the current script. But what is the current script?
A web app makes use of multiple files. So how do i get the dir of server.js?
EDIT: Here is a code example:
// routes.js
const spawn = require('child_process').spawn;
const fs = require('fs');
module.exports = function(app)
{
//the file upload button does a POST the the '/' route
//i left the arrow function notation for reference
app.post('/', (req, res) => {
if (req.files)
{
var pathAndFileName = '/home/user1/Desktop/app/dataLocation/'+fileName;
As you can see, pathAndFileName is hardcoded.
It works on my system, but it does not for every system.
So i would like to be to get the location of the server.js file (in /dir1), inside the app.js file, so i can the append to the directory the '/dataLocation' + fileName.

If routes.js is in:
/home/user1/Desktop/app/dir1
And, server.js is in:
/home/user1/Desktop/app
And, then the file you're trying to get to is in:
/home/user1/Desktop/app/dataLocation
Then, from routes.js, you can get the directory of server.js with this:
const serverjsDir = path.join(__dirname, ".."); // go up one level
Or, you could get the whole path your edit seems to be looking for (in a dataLocation subdirectory below where server.js is) with this:
const pathAndFileName = path.join(__dirname, '../dataLocation', fileName).
More detail
If you're using CommonJS modules (that use require()), then you can get the current script's directory with __dirname and then it's up to you to know where other resources are relative to your own directory so you can navigate up or down the directory hierarchy from __dirname. For example, if you want to get access to a file main.css in another directory at the same directory level as your script file, you could construct at path like this:
let filePath = path.join(__dirname, "../css/main.css");
But what is the current script?
The current script is the script that contains the code that is accessing __dirname.
A web app makes use of multiple files. Since the place where i want to embed the location (in its code) is located inside routes.js, i guess this is where is should target, am i correct?
It's not clear to me exactly what you mean here. If you can provide a specific example showing what code located in what directory wants to access what file located in what other directory, then we could offer you the precise code to get to that file.
If the code that wants to access this other file is in routes.js, then the location of routes.js would be in __dirname and you would build a relative path from that location as shown above.
To help you understand, __dirname is not a global variable. It's a module-specific variable that contains a different value for every single module location in your project. So, whatever code is running in whatever module will have access to it's own copy of __dirname that specifies the location of that specific code.

To get access routes.js, if it is a module, Im assuming you are using Import or Require, and you could use
require(./app/routes);
If you were to go back a directory, you use ../ as many times as needed. If this is not the answer you were looking for, either reply or someone else may answer

Related

Handling relative paths across modules in javascript

So let's say I have a .js file which exposes a function, which I want to be able to import in many other files. The function in this file needs access to some data stored in a certain file ( take .txt for this example) and I'm using the relative address to read and write to this text file.
Now the problem comes when I import this module into other files in different directories, the relative paths won't be valid but I don't know how I can change this? I'm sure there's a simple way to do this but I can't figure it out at all.
file 1
relative path = '../../file.txt'
function foo(){
fs.readFile(relativePath)
}
module.exports = {foo}
file 2
const {foo} = require('foo')
foo();
It doesn't actually matter which other modules load this module. The path is going to be resolved relative to the current working directory, which depends on in which directory your shell is in when you invoke the code.
If you want it to resolve relative to that specific JavaScript file, then you can use __dirname:
const path = require('path');
// ...
fs.readFile(path.join(__dirname, relativePath));
you can use resolve method of path package like
const path = require('path').resolve
path.resolve('../../file.txt')

How can I get the file path of a chosen file in ReactJS?

I'm currently creating an input in React by which a user can click on a button and open a browse box to select a file. The goal is to find the file path of the chosen file.
I'm aware that it is impossible to get the filepath from just a simple <input type="file"/> due to security reasons but I was wondering if there is a way to do it that I just haven't found or even a method in node that I could utilize by passing the file name to a node.js back end that could help me find the path.
I've also already looked into the fs-path npm package in node to find all paths and files so I could potentially match the file name to it's path but this doesn't help me if there is more than one file with the same name in a different path.
I can't seem to find any other suggestions except for just uploading the entire file's contents, which is not what I want to do.
Since I had to be able to run my application in a normal browser, something like ElectronJS wasn't viable for me to use. What I ended up doing instead was creating a back-end in Node JS and sending a request to the node back end for all files in a predetermined directory. I then used fs.readdir to return all the files and directories in the file and displayed them on my front-end React Application after which I allowed the user to choose a file or a directory. If a file was chosen, then I had my file path since I already knew what the current directory was. If a directory was chosen, another request was sent to the same API to get the files and directory of the new directory.
app.get('/api/fileFinder', async (req, res) => {
const mainDir = req.query.name || '/efs/data';
console.log(mainDir);
fs.readdir(mainDir, function(err, items) {
const dirs = [];
const files = [];
if (items){
for (var i=0; i<items.length; i++) {
if (fs.lstatSync(mainDir + '/' + items[i]).isDirectory()){
dirs.push(items[i]);
}
else{files.push(items[i])}
}
}
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({
files: files,
dirs: dirs
}));
});
In order to run both the ReactJS and the NodeJS on the same port, I built the ReactJS and added it to the NodeJS server by putting the build file into the same folder as the NodeJS file and adding app.use(express.static(__dirname + '/build')); to the NodeJS.
I hope this is helpful to anyone else facing a similar issue.

Is it necessary to specify directory when using appendFileSync?

I'm going through some of the nodejs documentation and starting to familiarize myself with some of the more basic functions. Specifically looking at appendFileSync function.
When trying to append a file, is it necessary to specify the directory? I don't recall this being a requirement in previous versions of Node but it seems when the directory is not specified, a new file is created in the root instead of appending the file.
I'm just trying to append a basic txt file, with this it creates a new file:
const fs = require('fs');
fs.appendFileSync('notes.txt', 'Changing the text with appendFileSync');
However, when specifying the directory, it appends the file just fine making me think this is required:
const fs = require('fs');
fs.appendFileSync('./nodejs/notes-app/notes.txt', ' Colin, changed the
text with appendFileSync', function (err) {
if (err) throw err; console.log('Notes updated');
});
Node -v 12.13.0
NPM -v 6.12.0
As with all fs operations that take a file path, if you don't specify any sort an absolute path, then the path you do specify is combined with the current working directory. In a nodejs program, the default current working directory (if you don't change it programmatically) is taken from the environment in which you started the node program.
If want to control the path directly without regard to the current working directory, then specify an absolute path.
This is what the fs module documentation says about file paths:
String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as specified by process.cwd().
Note: For some situations, a developer wants to access the file system relative to the installation of the module that is running. That is typically done by building a path that is relative to __dirname which is the location of the current module like this.
path.join(__dirname, "somefile.txt");
Of course, you can always specific a full path name starting from root if you want.

Install & access a local folder as a npm module

The file structure looks like this:
= (main-folder)
- package.json
- ...
= server
- index.js
- ...
= deploy-abc // new server
= src
- index.js
= src
- index.js
- ...
I am trying to install 'deploy-abc' as a module within the main-folder app. So, I ran : yarn add "/var/www/main-folder/deploy-abc". It installed correctly & I can see the 'deploy-abc' dependency listed in package.json.
However, when I try to access the deploy-abc's exported object, I get node error Error: Cannot find module 'deploy-abc'. E.g: In some file in the main folder:
const deployAbc = require("deploy-abc");
console.log(deployAbc); // error
Where am I going wrong?
As per the node docs: https://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders
If the module identifier passed to require() is not a core module, and does not begin with '/', '../', or './', then Node.js starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location.
So, seeing as your module is now in the main folder, how you require it will depend on the relative location. If you are requiring it from say /src/index.js, then you will need:
const deployAbc = require('../deploy-abc')
You also don't need to specify the actual file in this case, as it defaults to index.js. If however the entry file was say, dabc.js or something else, you would need to also specify that in the location.
You might have to use the exact relative path. For example, const deployAbc = require("../deploy-abc")

I'd like to reuse code from another module in my Nodejs backend

I'm using the Yeoman Generator Angular Fullstack and I'd like to reuse JS code from different directories within my server directory. I'm referencing the file that has the functions I want like:
var something = require('/.path');
I get the error: "Cannot find module" in my terminal.
I tried a number of variations of the path working through all of the levels from server level down to file level where the given functions are contained. I looked at a few tutorials:
http://www.sitepoint.com/understanding-module-exports-exports-node-js/
AND
https://www.launchacademy.com/codecabulary/learn-javascript/node/modules
I clearly missed something. Each module of my nodejs has a controller with an exports.create function. All of my code for each module is contained within my exports.create function accept for other required modules. I have no problem requiring underscore or other libraries in my Node/Bower modules by the way.
To be as detailed as can be, I expected
var something = require('./directory/directory.controller.js');
var something = require('/.path');
The path you are using is likely incorrect. Probably you want to open the file called path.js contained in the same folder of the file from which you are importing it. In order to do that, you should change the import as follows :
var something = require('./path');
./path is a relative path where . stands for current directory.
/.path is an absolute path. In this case require is importing a hidden file in the root directory. I guess is not what you want.

Categories

Resources