why is this code showing cannot find module error? - javascript

inside localbase.js...
const fs = require("fs");
if(!fs.existsSync(__dirname + "/localbase.json"))
fs.writeFileSync("./localbase.json", "{}");
let database = require("./localbase.json");
This above code is showing this error Error: Cannot find module './localbase.json'.
The file is imported in server.js as follows.
const lb = require('./db/localbase.js');
my directory structure (apology if my tree looks bad)...
|- db
+--- localbase.js
|- node_modules
|- public
server.js
package.json
But if I put the localbase.js where the server.js is then it's perfectly fine.

so the fix is real simple...
const fs = require("fs");
if(!fs.existsSync(__dirname + "/localbase.json"))
fs.writeFileSync(__dirname + "/localbase.json", "{}");
let database = require(__dirname + "/localbase.json");
So basically what I did is I imported relative the root directory(where the node_modules is) which was causing that error.
I thought using require('./localbase.json') would choose the directory relative to server.js but it won't.
So what I learnt is require() uses paths relative to root directory.
Which means I have to use __dirname to import modules inside of sub-directories.

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"?

How do I use "stream.pipe(fs.createWriteStream())"

How do I use stream.pipe?
I'm running a function that outputs:
const fs = require('fs');
const screenshot = require('screenshot-stream');
const stream = screenshot('http://google.com', '1024x768');
stream.pipe(fs.createWriteStream('picture.png'));
My next step is taking that picture (picture.png) and assigning it here:
var content = fs.readFileSync('/path/to/img')
In other words, what is the path to the image so I can upload it?
Lets say, Your project directory name is "PROJECT", And you executed this file from the root directory of your project, Then the PICTURE.png file will be created in the root directory.
And the path to that file'll be __dirname + "/PICTURE.png" if you are still in the root directory of your project.

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.

NodeJS cannot find custom module

I am trying to export a module to my routes file.
My file tree goes like
routes.js
app.js
controllers/users.js
posts.js
on my app.js I exported var route = require('./routes'); and that works.
now on my routes.js I tried to export require('./controllers');.
But it keeps telling me that it cannot find module controllers.
Doing this works:
require('./controllers/users')
But I am trying to follow expressjs sample initial projects format.
And it is bugging me because the example of expressjs shows: (express routes is a folder)
var routes = require('./routes');
and loads it like
app.get('/', routes.index);
with no error. and that ./routes is a folder. I am just following the same principle.
If you try to require a directory, it expects there to be an index.js file in that directory. Otherwise, you have to simply require individual files: require('./controllers/users'). Alternatively, you can create an index.js file in the controllers directory and add the following:
module.exports.users = require('./users');
module.exports.posts = require('./posts');
and then import: var c = require('./controllers');. You can then use them via c.users and c.posts.
You have to understand how require() works.
In your case it fails to find a file named controller.js so it assumes it's a directory and then searches for index.js specifically. That is why it works in the express example.
For your usecase you can do something like this -
var controllerPath = __dirname + '/controllers';
fs.readdirSync(controllerPath).forEach(function(file) {
require(controllerPath + '/' + file);
});
From:
http://nodejs.org/api/modules.html
LOAD_AS_DIRECTORY(X)
If X/package.json is a file, a. Parse X/package.json, and look for "main" field. b. let M = X + (json main field) c.
LOAD_AS_FILE(M)
If X/index.js is a file, load X/index.js as JavaScript text. STOP
If X/index.node is a file, load X/index.node as binary addon. STOP
So, if a directory has an index.js, it will load that.
Now, look # expressjs
http://expressjs.com/guide.html
create : myapp/routes
create : myapp/routes/index.js
Taking some time to really read how modules work is time well spent. Read here

Categories

Resources