Generator functions in node 0.12 - node.js

Are generator functions supported in Node? I keep reading that they are since v 0.11.
Tried to run this snippet in node 0.12
function* range(max, step) {
var count = 0;
step = step || 1;
for (var i = 0; i < max; i += step) {
count++;
yield i;
}
return count;
}
but no luck. Do I need to call npm start with a custom parameter?

You need to run node with --harmony flag to enable generators in node (0.11.x and 0.12.x versions):
$ node --harmony your_script.js

Related

Getting error while using Imagemagick npm

I am using Imagemagick npm in node to compress an image. I installed the npm module and it was working fine. But after some time, it throws the error shown below.
TypeError: currentLine.search is not a function
If I install the module again, it doesn't show the error. But again after some time, it throws the same error. I am using 0.1.3 version of Imagemagick with 8.9.1 version of node.
Can any one help me with this issue?
Even I got the same issue for 0.1.3 npm version. After some debugging, I found that if we add custom functions into Array.prototype like this
Array.prototype.asyncforEach = async function(cbk) {
for (let i = 0; i < this.length; i++) await cbk(this[i], i, this);
};
Which will leads to an error in file node_modules/imagemagick/imagemagick.js at line number 113 i will have asyncforEach as a value so we have to change our Array.prototype.methodName like below or reference this for better understanding.
Object.defineProperty(Array.prototype, 'asyncforEach', {
value: async function(cbk) {
for (let i = 0; i < this.length; i++) await cbk(this[i], i, this);
}
});

Making ESLint work for files which are loaded by others

I have a set of scripts in which one loads another script file and uses the functions defined in it.
For example, let's say I have main.js script with the following source
load("helper.js");
var stdin = new java.io.BufferedReader( new java.io.InputStreamReader(java.lang.System['in']) );
function readline() {
var line = stdin.readLine();
return line;
}
var N = parseInt(readline());
for(var i = 0; i< N; i++)
{
print("fd630b881935b5d43180ff301525488a");
var num = parseInt(readline());
var ans = perfectNumberCheck(num);
print(ans);
print("dc29e6fa38016b00627b6e52956f3c64");
}
I have another script file, helper.js which has the following source
function perfectNumberCheck(num) {
if(num == 1)
{
return 0;
}
var halfNum = (num/2) + 1;
var sum = 0;
var retVal = 0;
for(var i=1 ; i < halfNum; i++){
if(num % i === 0){
sum = sum + i;
}
}
if(sum == num){
retVal = 1;
}
else {
retVal = 0;
}
return retVal;
}
As it can be seen, main.js uses the function perfectNumberCheck. Now, when I run ESLint on both the files using eslint main.js helper.js or by using eslint *.js, I get the no-unused-vars error 'perfectNumberCheck' is defined but never used even though it is being used in main.js.
I want to keep this error in the configuration but don't want ESLint to show it in such cases.
Is there a way to make ESLint resolve these dependencies without writing the entire code in a single script file?
You can add a comment like /* exported perfectNumberCheck */ to helper.js to tell no-unused-vars that the function is used elsewhere outside that file:
/* exported perfectNumberCheck */
function perfectNumberCheck() {
// ...
}
By itself, ESLint lints each file in isolation, so it will not resolve identifiers defined in other files. The /* exported ... */ comment and globals allow you to inform ESLint of dependencies in other files.
Since exported comments are intended to be used to indicate names that are used elsewhere by being present in the global scope, they have no effect when the file's source in not in the global scope. Specifically, quoting the docs:
Note that /* exported */ has no effect for any of the following:
when the environment is node or commonjs
when parserOptions.sourceType is module
when ecmaFeatures.globalReturn is true

Sort TypeScript files by dependencies in NodeJS

I have some files and some of them have dependencies some of them dont.
There are also cicle dependencies. I want to sort this files by this dependencies to concat the files later in the correct order.
This are TypeScript files, but I collect all files in a NodeJS program where I want to sort the TypeScript files.
Example (This are only random names):
There are two options here, the first is basically "you don't need to" and the other is use a tool to put Humpty Dumpty together.
Node will handle require for you if you use commonjs as your module arg when compiling your TypeScript, then when running Node will load the dependencies for you at runtime
You can concat/bundle your output with with tools like webpack/browserify which will analyze your dependencies and put the files/contents in the right order in a single output file
Thanks for some answers of things that I already knew, I found a correct answer by myself, here is my solution:
var stack = [];
var visited = [];
function topologicalSortUtil(item) {
visited.push(item.fullPath);
for (var i = 0; i <= item.dependencies.length - 1; i++) {
var dependency = item.dependencies[i];
if (visited.indexOf(dependency.fullPath) !== -1) {
continue;
}
topologicalSortUtil(dependency);
}
stack.push(item);
}
function topologicalSort(data) {
for (var i = 0; i <= data.length - 1; i++) {
var item = data[i];
if (visited.indexOf(item.fullPath) !== -1) {
continue;
}
topologicalSortUtil(item);
}
return stack;
}
DEMO
References:
https://en.wikipedia.org/wiki/Topological_sorting
https://www.youtube.com/watch?v=ddTC4Zovtbc
https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/TopologicalSort.java
You can place reference tags at the top of each file, and use the --out CLI option. TSC will figure out the rest. Circular dependencies won't break TSC, but you do need to take into account that something may not exist yet at runtime.
Shape.ts
/// <reference path="Test.ts"/>
Test.ts
/// <reference path="Vector.ts"/>
Vector.ts
/// <reference path="Group.ts"/>
/// <reference path="Shape.ts"/>

node.js native binding slower than php native extension

Hello i am currently trying to port a php-extension (native C) to a node.js native extensions.
i am using nan ->https://github.com/rvagg/nan - for api abstraction
i have the following node cpp code:
NAN_METHOD(Core::getInfo) {
NanScope();
int somevar=1;
Local<Object> return_obj = NanNew<Object>();
return_obj->Set(NanNew<v8::String>("int"),NanNew<v8::Integer>(somevar));
return_obj->Set(NanNew<v8::String>("version"),NanNew<v8::String>("teststr"));
NanReturnValue(return_obj);
}
and the following php-extension c code:
PHP_FUNCTION(core_get_info) {
int somevar;
if (array_init(return_value) == FAILURE) {
RETURN_FALSE;
}
add_assoc_long(return_value, "int", somevar);
add_assoc_string(return_value, "version", "teststr", 1);
}
when running the call to this function in 1000000 iterations the NODE variation is MUCH Slower.
test.php
for($x=0; $x<1000000; $x++) {
$i = core_get_info();
}
var_dump($i);
test.js
var x=0;
var i;
for(x=0; x<1000000; x++) {
i=core.getInfo();
}
console.log(i);
the factor seems to be about 170% slower in node than in php - has any one a tipp what i am doing fundamentally wrong in the node part.
edit: node version v0.11.14

How do I require a minimum version of node.js in my script?

I just found out that a script I wrote only works on node 0.10 because it uses readable events.
How do I require a minimum version of node.js in my script so that users know that they need to upgrade?
In package.json:
{ "engines" : { "node" : ">=0.10.3" } }
From the docs.
Edit, a programmatic way:
var pkg = require('./pacakge'),
semver = require('semver');
if(!semver.satisfies(process.version, pkg.engines.node)) {
// Not sure if throw or process.exit is best.
throw new Error('Requires a node version matching ' + pkg.engines.node);
}
Add this to top the top of your script.
var versionComps = process.versions['node'].split('.');
if (parseInt(versionComps[0]) === 0 && parseInt(versionComps[1]) < 10) {
console.log('Script requires node.js version >= 0.10');
process.exit(1);
};

Resources