how to access parent module data in child file in node.js - javascript

my file are like avilabele this sturucture.
sample.js is root file and test.js is avilable in xx folder.
sample.js
var name={
h:14
}
module.exports=name;
test.js
var name=require('./sample.js')
console.log(name.h);
when a run test.js code using command prompt :
node test.js
it gives error like :
Cannot find module './sample.js'

When you require a file with a relative path, it is relative to the file doing the require (see here). In test.js, require('./sample.js') will look for /path/to/xx/sample.js. Use require('../sample.js') since it is in the parent folder of test.js.

var name=require('../sample.js')
console.log(name.h);
You are requiring module from the parent directory with ".."

Related

Using Path Module in NODE.JS

I'm trying to store the absolute path of a file in a variable, exporting it through module.exports to use it in other files, for example, a file in another project folder, accessing it by require. After that, I use this variable as the path of the readFileSync method. Very well, when running the code in V.S Code, it works perfectly, but when I try to run it in the terminal, the path that appears is different! Why does it happen?
//path_module.js file code (located in 'path' folder):
const testPath = path.resolve('path','content', 'subfolder', 'test.txt');
console.log(testPath);
module.exports = testPath;
//fileSync_modules.js file code (located in 'fs' folder):
const fs = require('fs');
const testPath = require('../path/path_module')
const readFile = fs.readFileSync(testPath, 'utf8');
console.log(readFile);
When I run in VS. Code, the content of test.txt is visible. When I run in terminal, it gives a path error:
Error: ENOENT: no such file or directory, open 'C:\\Users\\home\\alvaro\\node\\fs\\path\\content\\subfolder\\test.txt'
As I'm running inside fs folder, it recognizes this folder as part of the path.
It looks like you're trying to make an path relative to the source file.
To do this, add __dirname to the start:
const testPath = path.resolve(__dirname, 'path','content', 'subfolder', 'test.txt');

"." not being parsed as part of a require() Node.js

I've been working on a project and ran into an issue when I was reorganizing my files. The "." on my requires are not being parsed.
When I run my program I get a
Error: Cannot find module './src/map/createMap.js'
Here is my code:
server.js (main file):
process.chdir(__dirname);
//Completely unrelated code...
const gameConsole = require('./src/backend/console.js');
gameConsole.start();
console.js:
const {createMap} = require('./src/map/createMap.js'); << Error thrown here
const Server = require('./server.js').Server; << Error thrown here if I use path.resolve()
I've tried using path.resolve(), and that works fine. When I log process.cwd() it has the path of my root directory (the one with server.js). I am considering storing the paths as global variables. Thanks for your help.
EDITS:
Sample of file structure:
(root)
|_server.js
|_src
|_backend
| |_console.js
|_map
|_createMap.js
Here is createMap.js, on my git repo: https://github.com/ArkinSolomon/zombie-fight/blob/master/src/map/createMap.js
From the code you've linked, the path to ./src/map/createMap.js in console.js is wrong.
The correct path would be
../map/createMap.js
Go up 1 folder ../ then you've access to map folder
And for server in console.js, the path would be:
const { Server } = require('../../server.js')
Go up 2 folder ../../ as console.js is 2 folders deep relative to server.js
What about to use "../map/createMap.js"?

JS, Browserify: function not defined

I have files as represented:
-js/
- calc.js
- tool.js
-index.html
calc.js is a node module of following structure:
module.exports = {
calculate: function() {...},
getPrecision: function() {...}
}
and tool.js use require and adds some functions, like that:
const fpcalc = require('./fpcalc');
function changeState() {
//some code using fpcalc
}
I used Browserify to generate bundle.js and added that as script src.
One of my buttons on HTML page is using onclick=changeState(). After clicking I'm getting
ReferenceError: changeState is not defined
at HTMLAnchorElement.onclick
Why is that? Is there any other way to make it work?
The function "changeState" is not exported in your tool.js.
That means it is only visible inside your bundle.js, but not outside.
Have a look at this: https://makerlog.org/posts/creating-js-library-builds-with-browserify-and-other-npm-modules
It shows you how to expose your code to the global namespace in javascript.
Here's a very simple way to make it work like you want.
const fpcalc = require('./fpcalc');
window.changeState = () => {
//some code using fpcalc
}
I have same error, here is my working example.
mac, browserify https://github.com/perliedman/reproject
Must use sudo install globally
sudo npm install -g brwoserify
https://github.com/perliedman/reproject
sudo npm install reproject // install locally is fine
Must manually create 'dist' folder for later output file use
Must use --s expose global variable function 'reproject' and or 'toWgs84' you will use later in browser js.
Without --s , will get 'reproject' undefined error . https://makerlog.org/posts/creating-js-library-builds-with-browserify-and-other-npm-modules
browserify --help will list all options.
-o means output file directory
browserify node_modules/reproject/index.js --s reproject -o node_modules/reproject/dist/reproject.js
HTML script tag include your above dist/reproject.js
Now, you will not get 'reproejct' undefined error
return reproject(_geometry_, ___from_projection, proj4.WGS84, crss)

Process.chdir() has no effect on require

Given the structure directory structure:
.
├── alpha.js
└── foo
└── beta.js
And file contents
alpha.js
module.exports = "alpha"
foo/beta.js
var cwd = process.cwd()
process.chdir('../')
var alpha = require('./alpha.js')
console.log(alpha)
process.chdir(cwd)
From within foo/beta.js. I'd like to be able to trick require into thinking that the current working directory is the project root. The example above does not work when the following is run.
node ./foo/beta.js
However if I switch over the code to within foo/beta.js to the following. Reading the file from the system and passing it to the npm module _eval.
updated foo/beta.js
var path = require('path')
var cwd = process.cwd()
process.chdir(path.join(__dirname, '..'))
var fs = require('fs')
var _eval = require('eval')
var alpha = _eval(fs.readFileSync('./alpha.js'))
console.log(alpha)
process.chdir(cwd)
This does work, which proves it should be possible with require as well. No matter where you run if from it will always require the file. node ./foo/beta.js or cd foo && node ./beta.js
Is there any way that I can prepend or set the directory that require uses from within the file?
From the node.js doc for require():
If the module identifier passed to require() is not a native module,
and does not begin with '/', '../', or './', then node starts at the
parent directory of the current module, and adds /node_modules, and
attempts to load the module from that location.
If it is not found there, then it moves to the parent directory, and
so on, until the root of the file system is reached.
From this, you can see that the current directory is not used in loading modules. The main takeaway here should be that modules paths are relative to the location of the current module. This allows modules to load sub-modules in a self-contained fashion without having to know anything about where the parent is placed in the directory structure.
Here's a work-around function that loads a module file descriptor from the current directory if the filename passed to it does not start with a path separator or a ..
var path = require('path');
function requireCWD(fname) {
var fullname = fname;
if (fname && fname.length &&
!path.isAbsolute(fname) &&
fname.charAt(0) !== '.') {
fullname = path.join(process.cwd(), fname);
}
return require(fullname);
}
Then, any filename you give to requireCWD that is not relative and does not start with a "." will be loaded relative to the current working directory. If you want to allow even "." and ".." to be relative to the current working directory, then you can remove that test for '.' from the function.

require node modules written in coffeescript

I have two files, one is a controller and another is a test for this controller, both are in coffeescript and are in the same folder:
The folder structure is:
-controller
--labels.controller.coffee
--labels.controller.spec.coffee
The labels.controller extract:
module.exports = {
getImages: getImages
}
I am trying to require it from labels.controller.spec to test it
I tried
labelsController = require('labels.controller')
and
labelsController = require('./labels.controller')
and
labelsController = require('/labels.controller')
But always there is an error like:
Error: Cannot find module '../labels.controller'
What I am doing wrong? Is any difference if you include a file written in coffeescript?
You need to compile it first with the coffee command. In your project source, run this command (assuming your project is written in coffeescript)
coffee -co output/ src/
Where src is your project folder. Then run the .js files in output with node.

Categories

Resources