NodeJS cannot find custom module - javascript

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

Related

Error: Cannot find module './src/handlers/buttons.js' after migrating all files to a ./src folder [duplicate]

Let's say I have this directory structure
/Project
/node_modules
/SomeModule
bar.js
/config
/file.json
foo.js
-
foo.js:
require('bar');
-
bar.js:
fs.readdir('./config'); // returns ['file.json']
var file = require('../../../config/file.json');
Is it right that the readdir works from the file is being included (foo.js) and require works from the file it's been called (bar.js)?
Or am I missing something?
Thank you
As Dan D. expressed, fs.readdir uses process.cwd() as start point, while require() uses __dirname. If you want, you can always resolve from one path to another, getting an absolute path both would interpret the same way, like so:
var path = require('path');
route = path.resolve(process.cwd(), route);
That way, if using __dirname as start point it will ignore process.cwd(), else it will use it to generate the full path.
For example, assume process.cwd() is /home/usr/node/:
if route is ./directory, it will become /home/usr/node/directory
if route is /home/usr/node/directory, it will be left as is
I hope it works for you :D

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

Obtaining path in nodejs

My Directory structure is something as below:
app/
server/
api/
user/
controller.js
images/
image1.jpeg
The problem is when reading image1.jpeg within controller.js I have to use a string like
var imagePath = __dirname + '/../../../images/images1.jpeg';
fs.readFile(imagePath, ()....
now the above works FINE. however what I don't like is this string '/../../../'
is there a better way to access files in the images/ folder ?
You could use path.relative. You'd probably want to save these as constants but you could do the following to make things more readable.
Pass in the path to your current directory as the first parameter and the path to the image itself from the same parent directory (in this case app) and it will return the relative path from the current directory to the image.
// returns '/../../../images/images1.jpeg'
var relativePathToImage = path.relative(
'/app/server/api/user',
'/app/images/images1.jpeg');
var pathToImage = __dirname + relativePathToImage;
Short of passing the path to app/images to the controller, that's about as good as you can do.
You could traverse the module.parent references until module.parent isn't set, if you can safely make assumptions about where your main script is. For example, if your main script is app.js inside app/, you could do something like:
var path = require('path');
var topLevel = module;
while (topLevel.parent)
topLevel = topLevel.parent;
topLevel = path.dirname(topLevel.filename);
var imagesBasePath = path.join(topLevel, 'images');
// ...
fs.readFile(path.join(imagesBasePath, 'images1.jpeg'), ...);
I use an npm module called node-app-root-path to help me manage my paths within the NodeJS application.
See:
https://github.com/inxilpro/node-app-root-path
To obtain the application's root path you would do require('app-root-path');
Example:
global.appRoot = require('app-root-path');
var imagePath = global.appRoot.resolve('server/images');
var img1 = imagePath + '/image1.jpeg';
fs.readFile(img1, ()....
Not sure whether is it a good idea or not but for this case I have stored the appRoot as a global variable and this is so that it will be available anywhere within my NodeJS application stack, even to some of my other NodeJs libraries.
There are many other usages noted in their documentation, have a look and see if it helps you too.

how to write file with node webkit js?

When I build my app, 'fs' module doesn't work. So, it must write file, but when I start my app nothing happens. But if I start my app with:
$ /path/to/app nw
It works correctly. What's wrong?
Some code, where I use fs:
function check_prob_2(){
console.log('Problem 2');
fs.appendFile('log.txt', 'Checking problem 2: \n\n');
...
}
I use that function, but it doesn't work. It doesn't work only after build application. I build it with this guide
Try this:
Include the following (standard) module:
var path = require('path');
Specify the path as follows:
fs.appendFile(path.resolve(__dirname, './log.txt'), 'Checking problem 2: \n\n');
More info on the __dirname global can be found here.
EDIT
Since __dirname is not defined in node-webkit, you'll have to use the following workaround:
Make a file util.js or however you want to call it, containing this line:
exports.dirname = __dirname;
The __dirname variable can now be exposed in your main file:
var dirname = require('./util.js').dirname;
And replace __dirname by dirname in the code.
Details here

Require all files in the list of folder without adding them individually in JS [duplicate]

This question already has answers here:
node.js require all files in a folder?
(15 answers)
Closed 9 years ago.
I dont know much about node.Is there anything I can do to iterate the objects without having to require it everytime
folderOrder = ['routes', 'models','fixtures', 'views', 'controllers']
require 'routes/posts_route'
require 'routes/post_route'
require 'models/post'
Is there anyway all the new files I create in folders routes and models will be automatically required without having to require each one of them. My case for this example is https://github.com/abhayathapa/ember-blogger/blob/master/app/initialize.coffee
Any help will be greatly appreciated. I have tried the answers in node.js require all files in a folder? but I get the same --- Cannot find module "fs"
You could try something like this (if you were using node.js):
folderOrder = ['routes', 'models','fixtures', 'views', 'controllers']
fs = require 'fs'
folderOrder.forEach (folder) ->
dir = __dirname + '/' + folder + '/'
files = fs.readdirSync dir
files.forEach (file) ->
require dir + file
UPDATE
After examining the example you linked, it seems that this has nothing to do with node. It's browser code, that uses brunch for managing build. However, in the initialize.coffee, there is already a commented code snippet which does exactly that, and it seems to work if you uncomment it, and comment out the 'manual' requires. I don't know why it is not used in the first place, though.
So, initialize.coffee should contain this:
# ===== Config =====
window.App = require 'config/app'
require 'config/router'
require 'config/store'
# Load all modules in order automagically.
# Ember likes things to work this way so everything is in the App.* namespace.
folderOrder = [
'routes', 'models','fixtures', 'views', 'controllers', 'helpers', 'templates'
]
folderOrder.forEach (folder) ->
# Go through the prefixes in order and require them
window.require.list().filter((module) ->
new RegExp("^#{folder}/").test(module)
).forEach((module) -> require(module))
After editing the file, run brunch w -s from the root folder and it should be working.
Yep I'm using something like :
fs = require 'fs'
requiredFiles = {}
for file in fs.readdirSync __dirname when file isnt 'index.coffee'
requiredFiles[file.replace /\.coffee$/, ""] = require "./#{file}"
# requiredFiles is populated with all files in the current path, except index.coffee
I would do something similar to #mutil, but would instead put that logic in each given folder.
Given an array of paths, an index.coffee in each folder:
fs = require 'fs'
module.exports = (path)->
fs.readdir "./#{path}", (err, files) ->
if err?
return err
else
return (require "./#{file}" for file in files when file isnt 'index.coffee' and file isnt '.DS_Store')
with
for folder in folderOrder
require("./#{folder}")(folder) for folder in folderOrder
in initialize.coffee, but you may run into some async issues depending.

Categories

Resources