Within a karma test beforeEach) block I would like to access (read) a file from the project directory. However, I do not know how to get access to that directory, since process.cwd() returns the directory the test is running in, which is a random private dir assigned by node or gulp.
How can I find what the project dir is within a running test?
describe.only('convertClaimTypes', function () {
var claimTypes;
before(function () {
var base = process.cwd();
claimTypes = fs.readFileSync(path.join(base, 'build/resources/claimTypes.json'));
claimTypes = JSON.parse(claimTypes);
});
...
Try using __dirname in place of process.cwd() as it gives you the directory of the current file rather than the directory of the executable.
For example, if your tests are within a directory /test and /build is a directory within the root of your application, access /build from /test like so:
path.resolve(__dirname, '../build/');
Related
src/test.js
module.exports.test = function() {
const { readFileSync } = require('fs');
console.log(readFileSync('test.txt', 'utf8').toString())
}
index.js
const { test } = require('./src/test.js');
test();
Which results in No such file or directory. Does module.exports or exports not work when requiring files in another directory?
When you do something like this:
readFileSync('test.txt', 'utf8')
that attempts to read test.txt from the current working directory. That current working directory is determined by how the main program got started and what the current working directory was when the program was launched. It will have nothing at all to do with the directory your src/test.js module is in.
So, if test.txt is inside the same directory as your src/test.js and you want to read it from there, then you need to manually build a path that references your module's directory. To do that, you can use __dirname which is a special variable set for each module that points to the directory the module is in.
In this case, you can do this:
const path = require('path');
module.exports.test = function() {
const { readFileSync } = require('fs');
console.log(readFileSync(path.join(__dirname, 'test.txt'), 'utf8').toString())
}
And, that will reliably read test.txt from your module's directory.
I have the following structure:
-- node_modules
-- websites
---- common
------- config.js
---- testing
------- test.js
Inside config I have some variables set, which are being exported using module.export.
I am trying to retrieve those variables when running node test.js from config.js using the following codes:
var configData = require('./common/config.js')
var configData = require('../common/config.js')
None of them work. What can I do to retrieve the data from the other folder?
var configData = require('./../common/config.js');
./ is testing/
./../ is websites/
./../common/ is websites/common/
./../common/config.js is websites/common/config.js
from test.js:
const configData = require('../common/config');
You can safely omit '.js'.
As documentation say:
File Modules
If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions: .js,
.json, and finally .node.
.js files are interpreted as JavaScript text files, and .json files
are parsed as JSON text files. .node files are interpreted as compiled
addon modules loaded with dlopen.
A required module prefixed with '/' is an absolute path to the file.
For example, require('/home/marco/foo.js') will load the file at
/home/marco/foo.js.
A required module prefixed with './' is relative to the file calling
require(). That is, circle.js must be in the same directory as foo.js
for require('./circle') to find it.
Without a leading '/', './', or '../' to indicate a file, the module
must either be a core module or is loaded from a node_modules folder.
If the given path does not exist, require() will throw an Error with
its code property set to 'MODULE_NOT_FOUND'.
More info about how require() work here.
const cheerio = require('../node_modules/cheerio');
const request = require('../node_modules/request-promise');
const vl = require('../node_modules/validator');
const crypto = require('crypto');
const fs = require('fs');
Folder structure of my express js app look like this
I am trying to load a modules folder which is located in root directory
routes/users.js
var express = require('express');
var router = express.Router();
var md=require('./modules');
/* GET users listing. */
router.get('/',function(req, res, next) {
//res.send('respond with a resource');
console.log('test');
res.status(200).json({ error: 'message' });
});
module.exports = router;
But i am getting a module not found error:
Cannot find module './modules'
Note:
If modules folder is in node_modules folder require works fine,but getting module name error if its in project root directory,
also an index.js file is present in modules folder
Module resolution in NodeJS is relative to the directory of your dependent module when your resolution starts with ..
In other words :
var module = require('../modules'); // Since your file is in `./routes/index`
// and `module` is in `./modules/index`
If you don't supply . in front of the required module, then NodeJS will look for that module in node_modules directory.
Excerpt from the documentation, which is self explanatory.
require(X) from module at path Y
1. If X is a core module,
a. return the core module
b. STOP
2. If X begins with './' or '/' or '../'
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"
So in your case when you require('./modules'). NodeJS looks for it in the current directory ./routes, then since it can't find it, goes to look at it in node_modules.
Instead of './modules' you can try require('../modules')
I ran
node src/app.js
in the mean-to directory
express.static('public')
would work,why?
don't need to specify the path?
what's the rule?
and I know
__dirname+'/../public'`
works just fine.
Just want to make sure the the logic here
I look up the doc
http://expressjs.com/en/starter/static-files.html
it says
"Pass the name of the directory that contains the static assets to the express.static middleware function to start serving the files directly. "
"the path that you provide to the express.static function is relative to the directory from where you launch your node process"
Does that mean
if I run node src/app.js in mean-to folder --> use express.static('public')
if I run node app.js in src folder => use express.static('../public')
and for safety, better use __dirname to get the absolute path of the directory
Express static uses resolve function from module path
Example using path:
var p = require('path');
p.resolve('public'); // will return your absolute path for `public` directory
So rules for express static the same as for path#resolve function
You can see more example in the docs for path module
What's the difference between p.resolve and __dirname?
path#resolve
p.resolve() resolves to an absolute path
path.resolve('public');
Will return your absolute path for public' directory(e.g "C:\projects\myapp\public")
path.resolve('src'); // => "C:\projects\myapp\src")
__dirname
__dirname - name of the directory(absolute path) from which you're currently running your app
file app.js
console.log(__dirname);
Running node app.js will print your absolute path for your app, e.g "C:\projects\myapp"
You mixed 2 lines in one... And both are necessary:
//This line is to say that the statics files are in public
app.use(express.static(__dirname + "/public"));
//This another line is to say that when call the route "/" render a page
app.get("/", function (req, res) {
res.send('Hello World!');
}
Probably, the reason is in running it from directory highter one level than dir with code? Try run it from src:
cd src
node app.js
I am trying to reference an html document in a "self containing" module. The module is comprised of two files:
app_root/node_module/my_module/main.js
app_root/node_module/my_module/header.html
main.js contains:
module.exports.test = function() {
var doc = fs.readFileSync('./header.html');
console.log(doc);
}
when i run my program in app_root/program.js
require('my_module').test();
When i start my app, the current working directory is set to app_root. When it tries to read ./header.html it breaks because the paths aren't correct.
How would I find directory of the installed module without knowing anything about what is running it?
You can use __dirname to refer to the path of the current script.
So main.js would become:
module.exports.test = function() {
var doc = fs.readFileSync(__dirname + '/header.html');
console.log(doc);
}