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

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));
}

Related

Module not found error when trying to use a module as a local module

I am trying to understand as how to make a local module. At the root of node application, I have a directory named lib. Inside the lib directory I have a .js file which looks like:
var Test = function() {
return {
say : function() {
console.log('Good morning!');
}
}
}();
module.exports = Test;
I have modified my package.json with an entry of the path to the local module:
"dependencies": {
"chat-service": "^0.13.1",
"greet-module": "file:lib/Test"
}
Now, if I try to run a test script like:
var greet = require('greet-module');
console.log(greet.say());
it throws an error saying:
Error: Cannot find module 'greet-module'
What mistake am I making here?
modules.export is incorrect. It should be module.exports with an s.
Also, make sure after you add the dependency to do an npm install. This will copy the file over to your node_modules and make it available to the require function.
See here for a good reference.
Update:
After going through some examples to figure this out I noticed, most projects have the structure I laid out below. You should probably format your local modules to be their own standalone packages. With their own folders and package.json files specifying their dependencies and name. Then you can include it with npm install -S lib/test.
It worked for me once I did it, and it'll be a good structure moving forward. Cheers.
See here for the code.

Why can node not find my module?

I am using node v0.12.5 with nwjs and I have defined my own custom module inside of my project so that I can modularise my project (obviously).
I am trying to call my module from another module in my project but every time I attempt to require it I get the error could not find module 'uploader'.
My uploader module is currently very simple and looks like:
function ping_server(dns, cb) {
require('dns').lookup(dns, function(err) {
if (err && err.code == "ENOTFOUND") {
cb(false);
} else {
cb(true);
}
})
}
function upload_files()
{
}
module.exports.ping_server = ping_server;
module.exports.upload_files = upload_files;
With the idea that it will be used to recursively push files to a requested server if it can be pinged when the test device has internet connection.
I believe I have exported the methods correctly here using the module.exports syntax, I then try to include this module in my test.js file by using:
var uploader = require('uploader');
I also tried
var uploader = require('uploader.js');
But I believe node will automatically look for uploader.js if uploader is specified.
The file hierarchy for my app is as follows:
package.json
public
|-> lib
|-> test.js
|-> uploader.js
|-> css
|-> img
The only thing I am thinking, is that I heard node will try and source the node_modules folder which is to be included at the root directory of the application, could this be what is causing node not to find it? If not, why can node not see my file from test.js given they exist in the same directory?
UPDATE Sorry for the confusion, I have also tried using require('./uploader') and I am still getting the error: Uncaught Error: Cannot find module './uploader'.
UPDATE 2 I am normally completely against using images to convey code problems on SO, but I think this will significantly help the question:
It's clear here that test.js and uploader.js reside in the same location
When you don't pass a path (relative or absolute) to require(), it does a module lookup for the name passed in.
Change your require('uploader') to require('./uploader') or require(__dirname + '/uploader').
To load a local module (ie not one from node_modules) you need to prefix the path with ./. https://nodejs.org/api/modules.html#modules_modules
So in your case it would be var uploader = require('./uploader');
This problem stemmed from using Node Webkit instead of straight Node, as stated in their documentation all modules will be source from a node_modules directory at the root of the project.
Any internal non C++ libraries should be placed in the node_modules directory in order for Node webkit to find them.
Therefore to fix, I simply added a node_modules directory at the root of my project (outside of app and public) and placed the uploader.js file inside of there. Now when I call require('uploader') it works as expected.
If you're developing on a mac, check your file system case sensitivity. It could be that the required filename is capitalized wrong.

Gulp: write output files to subfolder relative of src path

I'm trying to figure out how to write a Gulp task, using PostCSS, so that it outputs the resulting files in the postcss subfolder of their original path.
Imagine you have these files:
/app/styles/index.css
/app/elements/pages/home.css
/app/elements/pages/profile.css
And you want Gulp to output the postCSS process to:
/app/styles/postcss/index.css
/app/elements/pages/postcss/home.css
/app/elements/pages/potcss/profile.css
This is my current configuration, but it doesn't work:
gulp.task('css', function () {
return gulp.src([
'app/styles/index.css',
'app/elements/**/*.css'
], {base: './'})
.pipe(gulp.postcss([require('cssnext')()]))
.pipe(gulp.dest('postcss'))
});
In fact, with the abive configuration Gulp will output all files with their relative subdirectories inside one postcss folder in the root of your project.
Any idea how to fix it? Thanks!!
I've found a viable solution, using gulp-rename. This is the updated task configuration:
gulp.task('css', function () {
return gulp.src([
'app/styles/index.css',
'app/elements/**/*.css'
], {base: './'})
.pipe($.postcss([require('cssnext')()]))
.pipe($.rename(function (path) {
path.dirname += "/postcss";
}))
.pipe(gulp.dest('./'))
});
This works perfectly. If anyone though knows a way to do it without using additinal external plugins, just through Gulp basic API, please post it. Thanks! Cheers

Importing classes works at design time but not at runtime

I'm using Visual Studio 2013 (Update 3), Node.js Tools v1.0.20721.02 and Node.js v0.10.31
I'm trying to put each class into its own file.
At design time everything seems fine, intellisense is working and the code compiles without issues.
At runtime however, node tells me it cannot find the classes.
I've reproduced this again and again by creating a new Node console project in Visual Studio
SomeClass.ts
export class SomeClass
{
name: string;
constructor(name: string)
{
this.name = name;
}
}
app.ts
///<reference path="Scripts/typings/node/node.d.ts"/>
import some = require("SomeClass");
var instance = new some.SomeClass("Batman");
console.log(instance.name);
The generated javascript output looks like this:
SomeClass.js
var SomeClass = (function () {
function SomeClass(name) {
this.name = name;
}
return SomeClass;
})();
exports.SomeClass = SomeClass;
//# sourceMappingURL=SomeClass.js.map
app.js
///<reference path="Scripts/typings/node/node.d.ts"/>
var some = require("SomeClass");
var instance = new some.SomeClass("Batman");
console.log(instance.name);
//# sourceMappingURL=app.js.map
Runtime output
module.js:340
throw err;
Error: Cannot find module 'SomeClass'
at Function.Module._resolveFilename (module.js:338:15)
...
Visual Studio Solution structure
This is a standard solution created by the project template in Visual Studio,
shouldn't it just work out of the box?
I've seen quite a few related questions, including this one, which seem to solve the
the issues most people are having, but don't seem to solve my problem.
Try using require("./SomeClass") instead:
node.js resolves require differently when there is no path prepended (see here), so in this case you need to tell it to look in the current directory, not for a core module or inside an (inexistent) node_modules directory.
Further info on why it does not fail before runtime, given by the OP in the comments:
Apparently VS resolves everything whether you prepend './' or not and at runtime node requires './' to be prepended.
Run your program again adding the following line before your require:
console.log("cwd:%s", process.cwd());
And adjust the path you require so it starts at your current working directory (cwd).

access all files in folder in nodejs

is library versioning is supported in nodeJS?
i have folder like package/version/1.0/
and files under this path
test1.js
test2.js
script.js
//access the folder package of version 1.1
var lib = require('require-all')(__dirname + '/package/version/1.0');
test1.js
========
function sum()
{ a+b ;}
exports.sum = sum;
test2.js
========
function sub()
{ a-b ;}
exports.sub = sub;
in script.js file, can require the package/version/1.1 folder. but how can i access the function sum() and sub() in my script file? and is library versioning supported in nodeJS? is the above code is a sort of library versioning ?
First of all, i haven't seen versions of libraries in one package, most common way is to release new versions of packages and upload them online, defining the required version in a package.json dependencies , npm will take care of download & install
If you want to deprecate a certain version of your library online there is npm deprecate which is the right command for that job.
When you create new npm package you can define a main script which will handle the loading of all files inside the package.
Usually its called index.js or main.js and it will be used when someone calls require('<library>');
So you can try the following to achieve the "versioning"
index.js
var fs=require('fs');
var path=require('path');
var _packageJSON=require(__dirname+'/package.json');
var defaultVersion=_packageJSON.version;
module.exports=function(whichVersion){
whichVersion=whichVersion||defaultVersion;
fs.exists(whichVersion,function(_exists){
if(_exists==null){
throw new Error('Unable to load version : '+whichVersion+' : '+_packageJSON.name);
}else{
// require , 1.0/index.js
require(path.join(whichVersion,'index.js'));
}
}
}
and any script that has that package as dependency it can load it by simply calling
require("<library name>")(<version>) ex.
require("mylib")("1.0")
under each version inside the package, you can have index.js which loads/exports variables and functions properly.
The final structure should look like
my npm package main module
index.js file
versions directory
1.0/index.js file
util.js
fn.js
var.js
2.0/index.js file
util.js
fn.js
var.js
Hope it helps.

Resources