gulp watch not work when use absolute path? - javascript

I am setting a gulp development environment, but when I used an absolute path in gulp watcher, it didn't work.Does gulp watcher support absolute path?
gulpfile.js
gulp.task('watch', function() {
gulp.watch(
path.join(__dirname, 'public/css/**/*.css'),
gulp.parallel('dev:css', 'dev:cssImgs')
);
});

I found the same error, and sorry for necroing this question in 2019., but this problem isn't solved yet.
It seems that watch process only accept relative paths written in unix style. It won't accept absolute paths or even relative paths with back slashes (windows style).
Using node path to clear out the path won't help on windows, so only solution would be to use node path.normalize('..\\your\\relative\\path\\') and then replace \\ with /.
I wrote one simple function that I will normalize path in unix way no matter on which OS it's used.
/*
This plugin is used to fix path separators for dynamically created links used
for `gulp watch` command.
It converts links like
`../../some//path\with/wrong//\separators/`
to
`../../some/path/with/wrong/separators/`
It also replaces `~` with user home directory path
*/
module.exports = (oldPath) => {
const pathString = oldPath;
const fix = /\\{1,}|\/{1,}/;
const user_home = require('os').homedir();
return pathString.replace(new RegExp(fix, 'gm'), '/').replace(new RegExp(fix, 'gm'), '/').replace('~', user_home)
}
Save that code as fixPath.js and then use it in this manner:
const fixPath = require('./fixPath')
let badPath = '../../some//path\with/wrong//\separators/'
let goodPath = fixPath(badPath) // "../../some/path/with/wrong/separators/"

Related

Dockerode - custom folder for container

Since yesterday, I have been trying to make a separate folder for each container in the "folder" folder in node.js api using the docker Library called "dockerode". Unfortunately, I did not find any good solution that would work. I looked at the Pterodactyl Daemon (old) source code where they had it, but unfortunately it didn't work for me either. Do you know of any good solutions that could work well?
If you need any more info, I will write it for you here.
Have a nice rest of the day, Domi
Do you just want to create a temporary folder? If so you can just use the fs module:
const fs = require('fs');
exports.createTmpDir = (dir) => {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
};
exports.generateRandomString = (length = 15) => {
return Math.random().toString(36).substring(2, length);
};
you can use it like this:
// assume you call it from the root project directory
const root = ${process.cwd()}`;
// create a temp folder path. use this if you want to clean up later.
const tempDir = `${root}/tmp/${generateRandomString()}`;
createTmpDir(tempDir);
You can also use fs to copy or move your dockerfile in to that folder
Not sure if this answers your question or not?

Node.js absolute path

I'm trying to build a Electron app which quickly pull the machine info to the user. I'm trying to use the npm module 'shelljs' to be able to use shell script in a node environment. But Electron doesn't really support shelljs so I'm in a bit of a pickle. There is a workaround that includes to use the absolute path to the node binary. Not sure what they mean by that so I thought you guys could help out.
The workaround I got is taken from here where they say this:
Set it like any regular variable.
// This is inside your javascript file
var shell = require('shelljs');
shell.config.execPath = 'path/to/node/binary'; // Replace this with the real path
// The rest of your script...
This is my code where I get an undefined on the execPath:
const shell = require('shelljs')
const path = require('path')
shell.confic.execPath = path.join('C:', 'Program Files', 'nodejs', 'node_modules', 'npm', 'bin')
Am I interpreting the workaround the wrong way?
The spelling error that #Chirag Ravindra pointed out did the trick. After a bit of thinking I came to this solution:
shell.config.execPath = path.join('C:', 'Program Files', 'nodejs', 'node.exe')
//Thomas

Avoiding relative require paths in Node.js

I prefer to import dependencies without lots of relative filesystem navigation like ../../../foo/bar.
In the front-end I have traditionally used RequireJS to configure a default base path which enables "absolute" pathing e.g. myapp/foo/bar.
How can I achieve this in Node.js?
What you can do is use require.main.require which would always be the module path of the starting file. See https://nodejs.org/api/modules.html#modules_accessing_the_main_module
This means, that when you run
const x = require.main.require('some/file/path/y')
It would require it based on the base path of your starting file (that was invoked , node app.js meaning the app.js file).
Other options include using process.cwd() to get the starting path of your app, but that would be depending on where you invoke your node process, not the location of the file. Meaning, node app.js would be different than of you would start it one level up, node src/app.js.
Just to add to the other answer, you can put this few lines in your main file:
(function (module) {
let path = require('path')
let __require = module.constructor.prototype.require
let __cpath = __dirname
module.constructor.prototype.require = function (str) {
if (str.startsWith('package:')) {
let package = str.substr(8)
let p = path.resolve(__dirname, package)
return __require(p)
} else {
return __require(str)
}
}
})(module)
It extends your require in such way:
if path begins with package: (i.e. package:src/foo/bar) it translates it to require('/absolute/path/to/your/app/src/foo/bar'),
if it doesn't start with package: then it behaves like a normal require would.

Is it possible to require modules from outside of your project directory without relative paths?

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

process.env.PWD vs process.cwd()

I am using Meteor JS...and within my Meteor app I am using node to query the contents of different directories within the app....
When I use process.env.PWD to query the contents of a folder I get a different result from when I use process.cwd() to query the results of a folder.
var dirServer = process.env.PWD + '/server/';
var dirServerFiles = fs.readdirSync(dirServer);
console.log(dirServerFiles);
//outputs: [ 'ephe', 'fixstars.cat', 'sepl_30.se1', 'server.js' ]
vs
var serverFolderFilesDir = process.cwd() +"/app/server";
var serverFolderFiles = fs.readdirSync(serverFolderFilesDir);
console.log(serverFolderFiles);
//outputs: [ 'server.js' ]
using process.cwd() only shows server.js within the Meteor.
Why is this?
How is process.cwd() different from process.env.PWD?
They're related but not the same thing.
process.env.PWD is the working directory when the process was started. This stays the same for the entire process.
process.cwd() is the current working directory. It reflects changes made via process.chdir().
It's possible to manipulate PWD but doing so would be meaningless, that variable isn't used by anything, it's just there for convenience.
For computing paths you probably want to do it this way:
var path = require('path');
path.resolve(__dirname, 'app/server')
Where __dirname reflects the directory the source file this code is defined in resides. It's wrong to expect that cwd() will be anywhere near that. If your server process is launched from anywhere but the main source directory all your paths will be incorrect using cwd().

Categories

Resources