There are no details about isFile() function in documentation of fs.Stats class
How it works? What exactly it checks?
At the OS level an entry for a given entry is marked as either a file or a directory entry. That information does not appear to be directly surfaced in the fs.Stats data structure, but it is something that the isFile() method can tell from the fs.Stats data structure.
By looking at the code for fs.js in node.js, you can see these:
fs.Stats.prototype._checkModeProperty = function(property) {
return ((this.mode & constants.S_IFMT) === property);
};
fs.Stats.prototype.isFile = function() {
return this._checkModeProperty(constants.S_IFREG);
};
Which shows that the information is contained within the mode property of the fs.Stats data structure.
Related
I have the following code:
MyUser.find().then(function (res) {
console.log(res[0]);
});
This effectively logs a model instance, which is fine. However, if I try to do this:
MyUser.find().then(function (res) {
delete res[0].name;
console.log(res[0]);
});
This delete statement doesn't work. Anyone knows why?
You did not provide any detail about the elements of the res array, but here is a possible cause.
Properties added to an Object using Object.defineProperty(obj, prop, descriptor) are, by default, immutable. Specifically, the descriptor property configurable, which defaults to false, determines whether the property is deletable.
I copied the code from kraken. I don't understand why there is a space between get and app(). Can someone please explain what's going on here?
var kraken = {
get app() {
return this._app;
},
use: function (route, delegate) {
//.....
}
}
No, in javascript a function cannot contain spaces. The code you are showing is using the get keyword to bind a property to a object.
get
Binds an object property to a function that will be called when that property is looked up.
Have a look to getters and setters in javascript.
It's a getter.
Check out this link.
The function is get and it's exposing a property called app.
For arrays I know you can do something like this:
function() {
}.observes("array.#each")
What I did was convert the object into an array and observe the properties with a #each, but is there a better way to observe object all property changes without converting it into an array?
You can observe isDirty to see if any of the object's values have been modified since last save (if you are using Ember Data).
Alternatively you can pass a comma separated list of properties to observes. This might be long if you have a lot of properties on your object, but will work.
A third approach could be to override setUnknownProperty() and set a property, a 'dirty flag' (or perform any action you may want in there.
There's also an old SO post that gives the following answer:
App.WatchedObject = Ember.Object.extend({
firstProp: null,
secondProp: "bar",
init: function(){
this._super();
var self = this;
Ember.keys(this).forEach(function(key){
if(Ember.typeOf(self.get(key)) !== 'function'){
self.addObserver(key, function(){
console.log(self.get(key));
});
}
});
}
});
You could probably split this out into a Mixin to keep your code DRY.
probably you could create something like a blabbermouth mixin and override the set method to get notified of property changes:
App.BlabbermouthMixin = Ember.Mixin.create({
set: function(keyName, value) {
this.set('updatedProperty', keyName);
this._super(keyName, value);
}
});
and observe the updatedProperty property?
You can get a list of properties in an object and apply them to a new property:
attrs = Ember.keys(observedObject);
var c = Ember.computed(function() {
// Do stuff when something changes
})
Ember.defineProperty(target, propertyName, c.property.apply(c, attrs));
Here is a working jsbin. Creating an observer instead of a property should be possible using a similar approach.
obj.prototype.__proto__ = events.EventEmitter.prototype
I have seen the code above sometimes, and I google about it, they say this line copy all of the EventEmitter properties to the obj. And I also see the code like this:
obj.__proto__ = events.EventEmitter.prototype
So I am wondering if they are the same?
I saw the first usage in this article, in which the author gives the exapmle:
var events = require('events');
function Door(colour) {
this.colour = colour;
events.EventEmitter.call(this);
this.open = function()
{
this.emit('open');
}
}
Door.prototype.__proto__ = events.EventEmitter.prototype;
var frontDoor = new Door('brown');
frontDoor.on('open', function() {
console.log('ring ring ring');
});
frontDoor.open();
And he explains:
This line: Door.prototype.__proto__ = events.EventEmitter.prototype; Copies all of the EventEmitter properties to the Door object.
As to the second way, I saw it in the source of hexo, in the init.js, there are code:
var hexo = global.hexo = {
get base_dir(){return baseDir},
get public_dir(){return baseDir + 'public/'},
get source_dir(){return baseDir + 'source/'},
get theme_dir(){return baseDir + 'themes/' + config.theme + '/'},
get plugin_dir(){return baseDir + 'node_modules/'},
get script_dir(){return baseDir + 'scripts/'},
get scaffold_dir(){return baseDir + 'scaffolds/'},
get core_dir(){return path.dirname(dirname) + '/'},
get lib_dir(){return dirname + '/'},
get version(){return version},
get env(){return env},
get safe(){return safe},
get debug(){return debug},
get config(){return config},
get extend(){return extend},
get render(){return render},
get util(){return util},
get call(){return call},
get i18n(){return i18n.i18n},
get route(){return route},
get db(){return db}
};
hexo.cache = {};
// Inherits EventEmitter
hexo.__proto__ = EventEmitter.prototype;
// Emit "exit" event when process about to exit
process.on('exit', function(){
hexo.emit('exit');
});
The statements are not the same.
Rather than obj.prototype.__proto__ = events.EventEmitter.prototype, I'd expect to see something like Constructor.prototype.__proto__ = events.EventEmitter.prototype, (where Constructor is any kind of constructor function, so could have any name. They're often capitalized.) because the prototype property is typically only available on functions, and does not have any special meaning when defined as a property of a regular (non-function) object.
In other words, obj in first line of code given should be a (constructor) function to make sense, and it's very uncommon to see a function have such a generic variable name as obj.
If you'd share the source where you find the exact first statement, this may clear things up.
The second example is the simplest. There's no constructor involved. hexo is a plain object created with an object-literal. The author wants the EventEmitter methods to be available through the hexo method, so he assigns EventEmitter.prototype to the __proto__ property, which actually changes the prototype of hexo.
The first code example is somewhat more complex. Here the author wants to ensure that any objects that are constructed by the Door function will provide access to the EventEmitter methods. Any object constructed by the Door function will get Door.prototype as its prototype. This particular prototype now has the EventEmitter as its prototype, so the EventEmitter functions are accessible by going two steps up the prototype chain.
"Copies all of the EventEmitter properties to the Door object." - this particular comment is misleading. No properties are copied. The only that happens is this.
door = new Door
door.on("open", function() { console.log("door has opened")})
The prototype of door is now Door.prototype. If a property (in this case on) is not found when trying to access it, the JS engine will look at this prototype. The prototype of door - Door.prototype - has no on defined either, so the JS Engine will see if Door.prototype has a prototype. It does, in the form of events.EventEmitter.prototype. And this object does have an on property defined.
Hope this makes things somewhat more clear. Javascript prototypical inheritance is quite tricky.
See also Confusion about setting something.prototype.__proto__
The prototype property is generally found on constructors, that is, Functions that create new objects. The prototype of a constructor is the object that is used as the prototype for the newly instantiated object.
The __proto__ property of an object points to the object which was used as a prototype, when the object was first instantiated. It is non-standard, so there's no guarantee that your JavaScript engine will support it.
In your examples, you can see that they refer to Door.prototype and hexo.__proto__. The crucial difference here is that Door is a constructor, whereas hexo is an instance of an object.
However, Door.prototype is an instance of an object, so to get its prototype, you need to use __proto__.
In both instances, the RHS of the assignment is a constructor, so refers to prototype.
In summary, if you want the prototype that will be used by a constructor, use prototype. If you want the prototype of an instantiated object, you may be able to use __proto__.
In truth, you may better off just using Object.getPrototypeOf.
Source
Everything in JavaScript is object. And every object, it may be a function, {}, new Object(), in JavaScript has an internal property called [[Prototype]].
[[Prototype]] is the very reason for prototype inheritance in JavaScript. This internal property is exposed to the programmer through __proto__. This is a non-standard. Not all JS environments support this.
How does an object we create using constructor functions gets its [[Prototype]]?
Only objects whose [[Class]] is Function gets the property prototype. What it means is that every function declared when executed by the JS engine, it creates an object. Its [[Class]] is set to Function and a property prototype is attached to this function object.
By default this prototype is an object with one property constructor pointing to the function object.
When the above function is invoked as part of new operator like new constructorFn(), the JS engine creates an object, its [[Class]] property set to Object and [[Prototype]] property set to the object pointed to by the [[Prototype]] of the constructor function.
Since this new created object is of class Object, it does not have the prototype property.
In nutshell, __proto__ exists in every object. prototype exists, by default, only in objects whose [[Class]] is Function. What this means is only functions (created via function statement, function expression, Function constructor ) will have this property.
I'm working with Dust.js and Node/Express. Dust.js documents the context helpers functions, where the helper is embedded in the model data as a function. I am adding such a function in my JSON data model at the server, but the JSON response to the browser doesn't have the function property (i.e. from the below model, prop1 and prop2 are returned but the helper property is not.
/* JSON data */
model: {
prop1: "somestring",
prop2: "someotherstring",
helper: function (chunk, context, bodies) {
/* I help, then return a chunk */
}
/* more JSON data */
I see that JSON.stringify (called from response.json()) is removing the function property. Not sure I can avoid using JSON.stringify so will need an alternative method of sharing this helper function between server/client. There probably is a way to add the helper functions to the dust base on both server and client. That's what I'm looking for. Since the Dust docs are sparse, this is not documented. Also, I can't find any code snippets that demonstrate this.
Thanks for any help.
send your helpers in a separate file - define them in a base context in dust like so:
base = dust.makeBase({foo:function(){ code goes here }})
then everytime you call your templates, do something like this:
dust.render("index", base.push({baz: "bar"}), function(err, out) {
console.log(out);
});
what this basically does is it merges your template's context into base, which is like the 'global' context. don't worry too much about mucking up base if you push too much - everytime you push, base recreates a new context with the context you supplied AND the global context - the helpers and whatever variables you defined when you called makeBase.
hope this helps
If you want stringify to preserve functions you can use the following code.
JSON.stringify(model, function (key, value) {
if (typeof(value) === 'function') {
return value.toString();
} else {
return value;
}
});
This probably doesn't do what you want though. You most likely need to redefine the function on the client or use a technology like nowjs.