When I coded the d3-composite-projections, the following stuff worked:
The directory tree:
- composite-projections.js
|
|- test
| |- test.js
|- node_modules
Inside test.js, I required d3.js and then, loaded composite-projections.js to test it, the following way:
var d3 = require('../node_modules/d3/d3.js');
var composite_projection = require('../composite-projections.js');
...
This worked ok, but now I've changed my machine, and running the test gives me the following error:
Message:
d3 is not defined
Stack:
ReferenceError: d3 is not defined
at ~/d3-composite-projections/composite-projections.js:6:1
So it's like the required d3 doesn't work when called from composite-projections.js, as if it was never included.
Does somebody know why and why it used to work before?
Finally I solved the problem using the technique explained in this answer: Load “Vanilla” Javascript Libraries into Node.js.
It's possible to call a function passing the environment with the vm library.
Anyway, my solution used to work, which I can't understand.
Related
Let's assume the following example
ROOT
config
my.json
releases
today
index.js
current (symlink to today for example)
i would like to include the json file in my index.js file using a simple requirestatement, require('my.json')
The nodejs script would be launcher using node index.js or node fullpath/index.js
The problem encountered is that the require path will always resolve to releases/today/index.js instead of current/index.js. Because of this the inclusion of my json file is not correct.
The following techniques have been tried, followed by the output:
__dirname: /ROOT/releases/today
process.cwd(): /ROOT/releases/today
process.env.PWD: depending on the startup location of the script: / or /ROOT/current
require('path').resolve(__dirname)): /ROOT/releases/today
process.env.PWD doesn't always give stable results and i was wondering if there is something that has the same result.
In node.js, it seems I run into the same 3 filenames to describe the main entry point to an app:
When using the express-generator package, an app.js file is created as the main entry point for the resulting app.
When creating a new package.json file via npm init, one is prompted for the main entry point file. The default is given as index.js.
In some programs I have seen, server.js serves as the main entry point as well.
Other times, still, it seems as though there are subtle differences in their usage. For example, this node app directory structure uses index.js and server.js in different contexts:
app
|- modules
| |- moduleA
| | |- controllers
| | | |- controllerA.js
| | | +- controllerB.js
| | |- services
| | | +- someService.js
| | +- index.js <--------------
| +- index.js <-------------------
|- middleware.js
+- index.js <------------------------
config
+- index.js <------------------------
web
|- css
|- js
server.js <----------------------------
What are the differences, if any, between these three names?
Even though you can call the files anything you want, there's an advantage to calling the entry point index.js or server.js
Why index.js:
When you issue npm init it will set the main entry point of the module to index.js. Some people don't change it, so they end up naming their main entry point index.js. It means there's one less thing to do.
Why server.js:
If your node package is not going to be consumed by another package, but rather is a stand-alone app, then if you call your main entry point server.js, then you can issue npm start and start your app. npm start will run your server.js file by default. To change this behavior, supply a start script in package.json. If a start script exists, npm start will run that script instead.
app.js is just a convention -- the only advantage to it is that some IDEs, such as Visual Studio Code will default to app.js as the entry point of a program you debug. That way when using the most common framework, Express, which creates an app.js file, "it just works"
It's pretty simple!
If your application is to be used in other applications: index.js
If your application is NOT to be used in other applications: server.js or app.js
As stated earlier the reasons being, when invoking npm start, if not defined in package.json, looks automatically for server.js. And when including another module into your application, it looks for index.js.
Extra:
I also tend to only use index.js as a file name when this is automatically found somehow. This makes me aware if the file is invoked directly or indirectly.
When using npm init it makes the default index.js.
Where I work, we didn't really settle on a format, so we have some apps with index.js, some with server.js.
Also, in some we have a config.js file at the root level, others are in a config folder (so require(config/config.js).
We even have one where server.js is in a server folder.
The trouble comes when we want to automate our deployment process. It becomes like technical debt when we have to make a bunch of minor modifications for each service.
That said, pick a format that makes sense to you and stick with it.
In fact all are just names and you must be consistent in your own work as pointed out by #Oka in a previous answer.
The only valid point here is that modular nature of node may play an important role in your decision, as pointed out in Folders as Modules section of NodeJS documentation there are 3 ways in which a folder may be passed to require() as an argument and the second and a common one is to automatically load the index.js file from the folder, this is how a lot of NPM packages are built and as it is simple and standard according to automatically loading NodeJS feature. It seems the best choice if you are developing an NPM package.
In the end, as others pointed out, you can choose any of the three, or even another one, but stick to your decision. My decision was to always use index.js based on the mentioned fact above.
I am using node v0.12.5 with nwjs and I have defined my own custom module inside of my project so that I can modularise my project (obviously).
I am trying to call my module from another module in my project but every time I attempt to require it I get the error could not find module 'uploader'.
My uploader module is currently very simple and looks like:
function ping_server(dns, cb) {
require('dns').lookup(dns, function(err) {
if (err && err.code == "ENOTFOUND") {
cb(false);
} else {
cb(true);
}
})
}
function upload_files()
{
}
module.exports.ping_server = ping_server;
module.exports.upload_files = upload_files;
With the idea that it will be used to recursively push files to a requested server if it can be pinged when the test device has internet connection.
I believe I have exported the methods correctly here using the module.exports syntax, I then try to include this module in my test.js file by using:
var uploader = require('uploader');
I also tried
var uploader = require('uploader.js');
But I believe node will automatically look for uploader.js if uploader is specified.
The file hierarchy for my app is as follows:
package.json
public
|-> lib
|-> test.js
|-> uploader.js
|-> css
|-> img
The only thing I am thinking, is that I heard node will try and source the node_modules folder which is to be included at the root directory of the application, could this be what is causing node not to find it? If not, why can node not see my file from test.js given they exist in the same directory?
UPDATE Sorry for the confusion, I have also tried using require('./uploader') and I am still getting the error: Uncaught Error: Cannot find module './uploader'.
UPDATE 2 I am normally completely against using images to convey code problems on SO, but I think this will significantly help the question:
It's clear here that test.js and uploader.js reside in the same location
When you don't pass a path (relative or absolute) to require(), it does a module lookup for the name passed in.
Change your require('uploader') to require('./uploader') or require(__dirname + '/uploader').
To load a local module (ie not one from node_modules) you need to prefix the path with ./. https://nodejs.org/api/modules.html#modules_modules
So in your case it would be var uploader = require('./uploader');
This problem stemmed from using Node Webkit instead of straight Node, as stated in their documentation all modules will be source from a node_modules directory at the root of the project.
Any internal non C++ libraries should be placed in the node_modules directory in order for Node webkit to find them.
Therefore to fix, I simply added a node_modules directory at the root of my project (outside of app and public) and placed the uploader.js file inside of there. Now when I call require('uploader') it works as expected.
If you're developing on a mac, check your file system case sensitivity. It could be that the required filename is capitalized wrong.
I'm attempting to set up unit testing on an Angular/Browserify project using Karma, Karma-Jasmine, and Karma-Browserify. I'm on a Windows machine, for reference. karma-cli is on my global npm path, and karma, karma-jasmine, karma-browserify, and browserify are all local npm installs, using -D.
I'm trying to pull in a single spec file, which looks like:
var PhoneListCtrl = require('../../../public/js/app/controllers/phone-list');
describe('PhoneListCtrl', function() {
var scope,
ctrl;
beforeEach(function() {
scope = {};
ctrl = new PhoneListCtrl(scope);
});
it('should create "phones" model with 3 phones', function() {
expect(scope).not.toBe(undefined);
});
});
And I get the following error every time:
Uncaught Error: Cannot find module 'Cc/gGH'
I get this exact same error after cloning the following repos, installing karma and all plugins, and attempting to run their example test suites:
https://github.com/xdissent/karma-browserify
https://github.com/waye929/angular-browserify
What on earth am I doing wrong? The test spec module is found correctly, and karma seems to be finding all necessary plugins/preprocessors, but it appears that karma-browserify is tripping on the require statement in a spec every time, for reasons I cannot fathom.
I've uninstalled and reinstalled karma and all related plugins numerous times now, to no avail.
I managed to find a solution. The issue was caused by karma-browserify's own module name hashing function, which is incompatible with newer versions of browserify. There's a fork that deals with it by using browserify's hashing function:
https://github.com/voidlock/karma-browserify/commit/3afe3b7485f2e4723bba5ad1c5a730d560b8c234
There's a pull request pending but in the meantime you can use the fork by placing
"karma-browserify": "https://github.com/voidlock/karma-browserify/tarball/use-browserify-hash-function"
in your package.json (dev)dependencies section.
How should I configure multiple paths for require?
I have the following structure:
application
|-server
| |-main.js
| |-myClass.js
| |-myClass.js
| |-implementationClass.js
|-common
| |-myOtherClass.js
| |-anotherClass.js
| |-yetAnotherClass.js
|-client
| |-aClientClass.js
| |-anotherClientClass.js
| |-implementationClass.js
I want to be able to do something like this:
require('myClass');
require('myOtherClass');
How should I configure the multiple paths?
currently using require.paths gives me an error : Error: require.paths is removed.
I want to keep this structure as my application has to serve static .js files from shared and I want to avoid sharing server-side .js files.
Also the files use a require() function on the client which emulates the node.js require() and I don't want to use relative paths.
the catch is that when I call require('anotherClass') it has to work on the client and on the server. So using relative paths could work but I also have the require('implementationClass') which returns either the client implementation or the server implementation, and when they are called from the common classes this approach will fail.
Best practice to require sub-modules is by using relative paths:
require('./server/myClass');
require('./common/myOtherClass');
If you are using requirejs, you can configure aliases for client-side:
require.config({
baseUrl: "http://example.com/static/",
paths: {
"myClass": "./server/myClass",
"myOtherClass": "./common/myOtherClass"
}
});
I do recommend doing something like the above, but if you really want to be able to require them globally you can set or modify the NODE_PATH environmental variable before launching your app. require.paths was removed since it only caused problems.
global.mod = function (file){
return require (path.resolve ("../..", file));
};
var myClass = mod ("server/myClass");
var myOtherClass = mod ("common/myOtherClass");
Using require with a relative path for your own modules is a very*1/0 ugly and bad approach.