To read a file located in the document root of the sails project I currently use an absolute path.
/var/www/project/file.conf
How can I get the document root path in sails? Or how can I read the file in a controller by using relative path?
in Sails the root path is: sails.config.appPath
Since the main application file is app.js in the root folder, process.cwd() should work just fine for you.
To extend what #Maciej Maczor Kaczorowski posted...
var path = require('path').resolve(sails.config.appPath, 'file.conf');
or
var path = require('path').resolve(".", 'file.conf');
or
var path = require('path').resolve('file.conf');
or
var path = sails.config.appPath + 'file.conf';
or
var path = res.baseUrl + 'file.conf';
Related
here is what I mean, my file structure looks like this:
main folder
app.js
child folder
fille.js
I want to get the absolute path of app.js from file.js
So assuming you are inside file.js and want to get the absolute path of app.js, with child folder being fixed, you can use path.join():
const path = require( 'path' ).join( __dirname, '..', 'app.js' )
It's easy:
You can try path.resolve
try:
resolve = require('path').resolve
resolve('../../app.js')
You will need to provide the relative path and it will give you absolute path. Hope this is what you are looking for.
How about:
let path = __dirname.substr(0,__dirname.lastIndexOf('/'));
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.
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.
I'm trying to build a local library of JS modules to use in Node projects.
If a new project lives in /Users/me/projects/path/to/new/project/ and my library files are located in /Users/me/projects/library/*.js is there a way to access those files without using a relative path?
In /Users/me/projects/path/to/new/project/app.js you can require foo.js like so:
var foo = require('../../../../../library/foo') and that will work but that's clunky and if files move you'd have to update your relative paths.
I've tried requireFrom and app-module-path with no luck as they are relative to a project root.
Any ideas for how to require files from outside of your project dir?
Thanks in advance!
var librarypath = '/Users/me/projects/library/';
// or if you prefer...
// var librarypath = '../../../../../library/';
var foo = require(librarypath + 'foo.js');
... or dressed up a bit more ...
function requirelib(lib){ return require('/Users/me/projects/library/'+lib+'.js'); }
var foo = requirelib('foo');
var bar = requirelib('bar');
I had the same problem many times. This can be solved by using the basetag npm package. It doesn't have to be required itself, only installed as it creates a symlink inside node_modules to your base path.
const localFile = require('$/local/file')
// instead of
const localFile = require('../../local/file')
Using the $/... prefix will always reference files relative to your apps root directory.
Disclaimer: I created basetag to solve this problem
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.