I'm going through some of the nodejs documentation and starting to familiarize myself with some of the more basic functions. Specifically looking at appendFileSync function.
When trying to append a file, is it necessary to specify the directory? I don't recall this being a requirement in previous versions of Node but it seems when the directory is not specified, a new file is created in the root instead of appending the file.
I'm just trying to append a basic txt file, with this it creates a new file:
const fs = require('fs');
fs.appendFileSync('notes.txt', 'Changing the text with appendFileSync');
However, when specifying the directory, it appends the file just fine making me think this is required:
const fs = require('fs');
fs.appendFileSync('./nodejs/notes-app/notes.txt', ' Colin, changed the
text with appendFileSync', function (err) {
if (err) throw err; console.log('Notes updated');
});
Node -v 12.13.0
NPM -v 6.12.0
As with all fs operations that take a file path, if you don't specify any sort an absolute path, then the path you do specify is combined with the current working directory. In a nodejs program, the default current working directory (if you don't change it programmatically) is taken from the environment in which you started the node program.
If want to control the path directly without regard to the current working directory, then specify an absolute path.
This is what the fs module documentation says about file paths:
String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as specified by process.cwd().
Note: For some situations, a developer wants to access the file system relative to the installation of the module that is running. That is typically done by building a path that is relative to __dirname which is the location of the current module like this.
path.join(__dirname, "somefile.txt");
Of course, you can always specific a full path name starting from root if you want.
Related
I have my server.js file at let's say directory: /dir1
I start the server with node server.js.
I have my file routes.js in directory /dir1/app/.
I want to get the directory of the server.js file.
I am not too sure how to do this. I can place code that tells me the location of the current script. But what is the current script?
A web app makes use of multiple files. So how do i get the dir of server.js?
EDIT: Here is a code example:
// routes.js
const spawn = require('child_process').spawn;
const fs = require('fs');
module.exports = function(app)
{
//the file upload button does a POST the the '/' route
//i left the arrow function notation for reference
app.post('/', (req, res) => {
if (req.files)
{
var pathAndFileName = '/home/user1/Desktop/app/dataLocation/'+fileName;
As you can see, pathAndFileName is hardcoded.
It works on my system, but it does not for every system.
So i would like to be to get the location of the server.js file (in /dir1), inside the app.js file, so i can the append to the directory the '/dataLocation' + fileName.
If routes.js is in:
/home/user1/Desktop/app/dir1
And, server.js is in:
/home/user1/Desktop/app
And, then the file you're trying to get to is in:
/home/user1/Desktop/app/dataLocation
Then, from routes.js, you can get the directory of server.js with this:
const serverjsDir = path.join(__dirname, ".."); // go up one level
Or, you could get the whole path your edit seems to be looking for (in a dataLocation subdirectory below where server.js is) with this:
const pathAndFileName = path.join(__dirname, '../dataLocation', fileName).
More detail
If you're using CommonJS modules (that use require()), then you can get the current script's directory with __dirname and then it's up to you to know where other resources are relative to your own directory so you can navigate up or down the directory hierarchy from __dirname. For example, if you want to get access to a file main.css in another directory at the same directory level as your script file, you could construct at path like this:
let filePath = path.join(__dirname, "../css/main.css");
But what is the current script?
The current script is the script that contains the code that is accessing __dirname.
A web app makes use of multiple files. Since the place where i want to embed the location (in its code) is located inside routes.js, i guess this is where is should target, am i correct?
It's not clear to me exactly what you mean here. If you can provide a specific example showing what code located in what directory wants to access what file located in what other directory, then we could offer you the precise code to get to that file.
If the code that wants to access this other file is in routes.js, then the location of routes.js would be in __dirname and you would build a relative path from that location as shown above.
To help you understand, __dirname is not a global variable. It's a module-specific variable that contains a different value for every single module location in your project. So, whatever code is running in whatever module will have access to it's own copy of __dirname that specifies the location of that specific code.
To get access routes.js, if it is a module, Im assuming you are using Import or Require, and you could use
require(./app/routes);
If you were to go back a directory, you use ../ as many times as needed. If this is not the answer you were looking for, either reply or someone else may answer
Here is a code snippet from a gulp file. I'd like to understand passing of argument "file" to internal functions. More importantly, I'd like to understand this idiom because I see it often in Javascript. My guess is that "tsResult.js" iterates through various javascript files in this Typescript project and the "file" argument is each such file. How can I decipher such usage below and in future
gulp.task('scripts', ['clean'], () => {
const tsResult = tsProject.src().pipe(sourcemaps.init()).pipe(tsProject());
return tsResult.js.pipe(sourcemaps.write({
includeContent: false,
sourceRoot: function (file) {
return path.relative(path.dirname(file.path), file.base);
}
}))
.pipe(gulp.dest(OUTPUT_FOLDER));
});
Many JS libraries make heavy use of a design pattern called Dependency Injection.
Basically, gulp-sourcemaps is giving you the option of overriding how the source root (the root URL where the file is located) is determined.
From the gulp-sourcemaps documentation:
Set the location where the source files are hosted (use this when includeContent is set to false). This is usually a URL (or an absolute URL path), not a local file system path. By default the source root is '' or in case destPath is set, the relative path from the source map to the source base directory (this should work for many dev environments). If a relative path is used (empty string or one starting with a .), it is interpreted as a path relative to the destination. The plugin rewrites it to a path relative to each source map.
The sourceRoot function is called, passing in the file that is currently being processed, and is expected to return the root path.
If I have Grunt installed in some folder /foo, but my current folder is /foo/bar/baz, and I run "grunt sometask" from within my current folder, how can I get Grunt (or NodeJS for that matter) to determine my current path? That is to say, how can I programmatically GET the folder I was in when I called grunt?
When I use process.cwd(), I get the path of the gruntfile, ie, "foo", which is not what I want.
I don't have to do this in Grunt specifically, any nodejs-based solution would work.
According to the source code:
By default, all file paths are relative to the Gruntfile
And, voilá, this line of code shows how grunt actually changes the current directory to the path of the Gruntfile:
process.chdir(grunt.option('base') || path.dirname(gruntfile));
However, option --base is there for just that. See docs: http://gruntjs.com/api/grunt.file
If you don't need to do it from inside the Gruntfile, simply run a script that captures the process.cwd() and then execs grunt.
See: https://www.npmjs.com/package/exec
var exec = require('exec');
process.cwd(); // Will have your current path
exec(['grunt', 'mytask'], function(err, out, code) {
if (err instanceof Error)
throw err;
process.stderr.write(err);
process.stdout.write(out);
process.exit(code);
});
in the Mac or Linex, you can get this by
process.env.PWD
in the windows, unknown
You can edit the grunt-cli to get finish this.
grunt-cli/bin/grunt
require(gruntpath).cli({_originDir:basedir});
then in the gruntfile.js, you can follows:
grunt.option('_originDir')
I am trying to require a file relatively and mysteriously the following is happening
This works well which points to /Users/marcos/Desktop/Taper/lib/utils.js
myPath = "/Users/marcos/Desktop/Taper/lib/./utils";
require(myPath);
This doesn't but it should point to exactly the same file:
require.paths.unshift("/Users/marcos/Desktop/Taper/lib")
require("./utils"); //Doesn't work with './'
require("utils"); //Works Fine
Anyone knows why I can't still use ./ in this case for loading the path since
require("path").resolve("/Users/marcos/Desktop/Taper/lib", "./utils")
results in:
"/Users/marcos/Desktop/Taper/lib/utils"
anyway?
Thanks in advance
UPDATED:
From the documentation:
A 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 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 is either
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'.
Here’s the original answer, which refers to require.paths (which is no longer supported):
From the documentation:
In node, require.paths is an array of strings that represent paths to be searched for modules when they are not prefixed with '/', './', or '../'.
(emphasis mine)
You can pass that using NODE_PATH
Example:
NODE_PATH=`pwd` node app.js
I created a new node module called rekuire.
It allows you to "require" without using relative paths.
It's a big time saver when it comes to testing/refactoring.
https://npmjs.org/package/rekuire
In a Node.js module I would like to open a file--i.e, with fs.readFile()--that is contained in the same directory as my module. By which I mean it is in the same directory as the ./node_modules/<module_name>/index.js file.
It looks like all relative path operations which are performed by the fs module take place relative to the directory in which Node.js is started. As such, I think I need to know how to get the path of the current Node.js module which is executing.
Thanks.
As david van brink mentioned in the comments, the correct solution is to use __dirname. This global variable will return the path of the currently executing script (i.e. you might need to use ../ to reach the root of your module).
For example:
var path = require("path");
require(path.join(__dirname, '/models'));
Just to save someone from a headache.