glob paths don't work in my Windows environment - node.js

I don't know what happened, suddenly, all my applications that make use of glob paths broke.
Jasmine, TypeORM, any library I need to specify directories through of glob patterns don't work on my Windows.
I dove deeply into those libraries trying to solve the issue. I figured out that libraries use some path module's functions, like join and normalize, to handle the paths before passing them to the glob module. Let me show a code snippet from Jasmine library:
includeFiles.forEach(function(file) {
if(!(path.isAbsolute && path.isAbsolute(file))) {
file = path.join(jasmineRunner.projectBaseDir, jasmineRunner.specDir, file);
}
var filePaths = glob.sync(file, { ignore: excludeFiles });
C:\Users\User\Programmation\project\test***[sS]pec.js
The join function converts all slashes from path to backslashes, but the glob module doesn't recognize paths with backslashes. The same thing happens with TypeORM using the normalize function from the path module under the hood.
const allFiles = directories.reduce((allDirs, dir) => {
return allDirs.concat(glob_1.default.sync(PlatformTools_1.PlatformTools.pathNormalize(dir)));
}, []);
The curious thing is that everything has worked before. I don't know exactly when it stopped working, but it did.

I encountered a similar problem.
After digging inside the TypeORM code I realized the problem is with the glob library.
glob has a problem with the windows separator.
I ended up replacing the separator like this:
entities: [
(__dirname+"\\..\\entities\\**\\*.entity{.ts,.js}").replace(/\\/g,'/')
],

Related

What the "#" stands for in paths like "#/assets/xyz"?

Sometimes I see paths written like "#/assets/XXX", and I reckon it refers to the root maybe (in Nodejs)? But i guess it's a syntax that doesn't apply everywhere because when I want to refer to the root folder and try to use it, it sometimes break. I am not sure the implications of it.
The "#" is often used as an alias for a frequently used path (like src/) in webpack environments. You have to define it in your configuration file so the "#" can be resolved in the build-process.
If you work in an ES6 environment and import a component several times, it can be handy to create an alias for the component path.
Example (source: webpack documentation):
resolve.alias
object
Create aliases to import or require certain modules more easily. For example, to alias a bunch of commonly used src/ folders:
webpack.config.js
module.exports = {
//...
resolve: {
alias: {
Utilities: path.resolve(__dirname, 'src/utilities/'),
Templates: path.resolve(__dirname, 'src/templates/')
}
}
};
Now, instead of using relative paths when importing like so:
import Utility from '../../utilities/utility';
you can use the alias:
import Utility from 'Utilities/utility';
You can find a similar answer here: https://stackoverflow.com/a/42753045/10764912

Node.js Gulp src/dest 4.0 behaviour vs Gulp 3.6

Quick Summary of my question:
Does Gulp 3.6.0 dest() handle glob-base the same way as 4.0.0?
function other() {
return src([
path.join("src/**/*"),
path.join("!src/**/*.{html,css,js,scss}")
])
.pipe(fileFilter)
.pipe(dest(dist));
}
Running Gulp 3.6.0 with the code above produced this result:
Note that the folders and files in question added to the dist folder by this code were:
-app
-assets
-config
favicon.ico
Now running the same code in 4.0.0 produces this:
I know that the glob-base is added on by default to the destination when it's piped through, however is this behaviour different to how gulp handled mirroring source to dest file directory structure in 3.6.0? The example would suggest otherwise.
If anyone could provide me with a solution for producing the same folder structure as supplied in my 3.6.0 result that would be great. I've tried gulp-flatten and gulp-rename but nothing is producing the desired result of nicely removing only the glob-base.
So I'm still not sure what the significance of upgrading to Gulp 4.0 actually was with relation to how glob-parent/glob-base is handled however I managed to get what I needed using the base option.
This option effectively nullified the additional src hard-coded path reference before /**/ in the path.
function other() {
var fileFilter = plugins.filter(function(file) {
return file.stat.isFile();
});
var appFilter = plugins.filter(function(file) {
return file.path.indexOf("\\src\\app\\") === -1;
});
return src(path.join(conf.paths.src, "/**/*"), { base: conf.paths.src })
.pipe(appFilter)
.pipe(fileFilter)
.pipe(dest(conf.paths.dist));
}

Unable to delete file using fs.removeSync()

I am using angular 6. I want to delete multiple files from backend folder for that, I am using fs.removeSync() but it gives below exception for me.
can someone help me?
"UnhandledPromiseRejectionWarning: TypeError: fs.removeSync is not a
function "
My Code:
fs.removeSync('/NodeWorkspace/uploads/output/*.csv');
Based on node.js documentation removeSync function not exist. For delete file use unlinkSync function like this:
fs.unlinkSync(path)
But I don't think that work for multiple files, you can use glob package:
var glob = require("glob")
// options is optional
glob("/NodeWorkspace/uploads/output/*.csv", options, function (er, files) {
for (const file of files) {
fs.unlinkSync(file);
}
})
Note: Remember for delete directory use fs.rmdir();
fs.removeSync(path) is a function of fs-extra library which is a wrapper over fs provided by nodejs.
Try using fs.unlinkSync(path).

How can I make webpack skip a require

How can I make webpack skip occurences of
require('shelljs/global');
in my source files? I want to make a bundle of my source files but keep the require('shelljs/global') in the files and not bundle shelljs/global.
If you store the path in a variable then IgnorePlugin will not work. Though you still could do:
const myCustomModule = eval('require')(myCustomPath)
for new comers, on webpack 2+ the way to do this is like so:
module.exports = {
entry: __dirname + '/src/app',
output: {
path: __dirname + '/dist',
libraryTarget: 'umd'
},
externals: {
'shelljs/globals': 'commonjs shelljs/global'
}
};
the bundle will contain a verbatim require:
require('shelljs/global');
read on more supported formats on webpack's config guide and some good examples here
You can use Ignore Plugin (webpack 1) / Ignore plugin (webpack 2).
Add plugin in webpack.config.js:
plugins: [
new webpack.IgnorePlugin(/shelljs\/global/),
],
If require is in the global namespace and this is why you want Webpack to ignore it, just do window.require()
This should be a last resort option, but if you are certain that your JS file is always parsed by Webpack, and nothing else:
You could replace your require() calls with __non_webpack_require__()
Webpack will parse and convert any occurrence of this and output a normal require() call. This will only work if you are executing in NodeJS OR in a browser if you have a global require library available to trigger.
If webpack does not parse the file, and the script is run by something else, then your code will try to call the non-converted __non_webpack_require__ which will fail. You could potentially write some code that checks earlier in your script if __non_webpack_require__ exists as a function and if not, have it pass the call on to require.
However, this should be temporary, and only to just avoid the build errors, until you can replace it with something like Webpack's own dynamic imports.
Here a trick
const require = module[`require`].bind(module);
Note the use of a template string
If some files contains nested requires and You want to ignore them, You can tell webpack to not do parsing for these specific files.
For example if swiper.js and vue-quill-editor.js had inner requires this would be how to ignore them.
module.exports = {
module: {
noParse: [
/swiper.js/,/quill/
],

mocha fs.existsSync always failing

I am attempting to check if a file exists in my mocha test. I know for a fact that the file exists in the test folder(I am placing it there for simplicity while I try and get this to work). But no matter what I do, fs.existsSync always fails. Logger.startup() creates the file. Logger.getFilename() returns a value like 5-17-30-2013.log. I am new to mocha so have no clue if I am making a classic blunder. As far as I know I am using mocha synchronously. Thanks for all of the help.
Here is my Mocha Test script:
var logger = require('../logger');
var fs = require('fs');
describe("Logger", function () {
it("Creates a file", function () {
logger.startup();
console.log(logger.getFilename());
if (!fs.existsSync(logger.getFilename())) {
throw ("Logging File Does Not Exist");
}
})
})
The currently accepted self-answer's explanation falls short. It says:
Apearently fs looks at the root of the project, the package.json folder, and not realative to the file calling it, which I did not know.
Sure, but it's not happenstance or a quirk of the fs module. The fs module uses process.cwd() to interpret relative paths passed to it. Unless it is changed with process.chdir(), process.cwd() is the directory in which the current process has been started. Since mocha is usually launched from the root of a project, then in a mocha process, process.cwd() is usually going to be the root of the project. If mocha were launched from a different directory, then process.cwd() would have a different value.
The confusion may come from how the module system handles relative paths. A module name with a relative path will be interpreted relative to the __dirname of the current file. This may be a value different from process.cwd().
try using process.cwd() to determine the working directory fs.exists is running from
I believe you are looking for __dirname, try to prepend it to the filename.
Documentation: http://nodejs.org/api/globals.html#globals_dirname
I followed #jjm and his advice on the program. After logging where it thought the file was, it turns out that it was looking in the folder "logger", not "logger/test" Apearently fs looks at the root of the project, the package.json folder, and not realative to the file calling it, which I did not know.
You can use fs.open(filepath, 'r', callback);
http://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback
This worked for me:
describe("Logger", function () {
it("Creates a file", function (done) {
logger.startup();
console.log(logger.getFilename());
fs.readFile(logger.getFilename(), done);
});
});

Resources