I want to run d3 from a Cakefile - javascript

I'd like to execute some d3 code from the command line. Initially I just tried something like:
task 'data', 'Build some data with d3', ->
d3 = require('lib/d3.v2')
console.log "d3 version = "+ d3.version
But this didn't work. I got errors like this:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
ReferenceError: CSSStyleDeclaration is not defined
at /Users/mydir/Documents/classes/middleclass/app/lib/d3.min.js:1:21272
at Object.<anonymous> (/Users/mydir/Documents/classes/middleclass/app/lib/d3.min.js:2:25395)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Module.require (module.js:357:17)
at require (module.js:368:17)
at Object.action (/Users/mydir/Documents/classes/middleclass/Cakefile:22:10)
at /usr/local/lib/node_modules/coffee-script/lib/coffee-script/cake.js:39:26
So...I figured this exception was telling me that I need to execute d3 inside of a browser. I tried this in a couple different ways. Basically though, I thought if I just fired up phantomjs I'd probably be able to do what I wanted to do. Here was my Cakefile:
task 'data2', 'Build some data with d3', ->
hem = spawn 'hem', ['server']
phantom = require('phantom')
phantom.create (ph) ->
ph.createPage (page) ->
page.open 'http://localhost:9294/sandbox.html', (status) ->
page.evaluate (-> window), (window) ->
require = window.require
require('lib/d3.v2')
console.log("d3 version = "+ d3.version)
ph.exit()
hem.kill()
When I go this route though, I always end up getting exceptions like this:
TypeError: object is not a function
at Object.CALL_NON_FUNCTION (native)
at Object.<anonymous> (/Users/mydir/Documents/classes/middleclass/Cakefile:52:13)
at Object.<anonymous> (/Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode-protocol/index.js:274:16)
at apply (/Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode-protocol/index.js:143:17)
at EventEmitter.handle (/Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode-protocol/index.js:120:13)
at /Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode-protocol/index.js:81:20
at EventEmitter.<anonymous> (/Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode/node_modules/lazy/lazy.js:62:13)
at EventEmitter.<anonymous> (/Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode/node_modules/lazy/lazy.js:46:19)
at EventEmitter.emit (events.js:67:17)
at EventEmitter.<anonymous> (/Users/mydir/Documents/classes/middleclass/node_modules/phantom/node_modules/dnode/node_modules/lazy/lazy.js:46:39)
What am I doin wrong??
Thanks to mbostock I got the following working:
My package.json:
{
"name": "app",
"version": "0.0.1",
"dependencies": {
"d3": "~2.8.0",
"jsdom": "~0.2.13"
}
}
My Cakefile:
task 'd3', 'Do something with d3', ->
jsdom = require('jsdom')
jsdom.env({
html: 'public/sandbox.html'
done: (errors,window) ->
require('d3/index.js')
console.log("d3 version = "+ d3.version)
})

See D3's package.json. More specifically, the file you want to require when running inside Node or similar environments is index.js rather than d3.v2.js; this file contains some special patches that make D3 compatible with the require operator.
To try it out for yourself, cd to the d3 repository, run node to create an interactive shell, and then say
var d3 = require("./");
Or, if you're in your own project folder, if you've installed D3 into node_modules/d3 via npm (npm install d3), you can say:
var d3 = require("d3");

Related

Error: A dynamic link library (DLL) initialization routine failed on electron but it's fine on node js

I'm trying to load a custom module in electron written in D with node_dlang package, which is fine with node, but it fails within electron.
the test with node, that runs just fine, goes like this:
const nativeModule = require('./module.node');
const assert = require('assert');
assert(nativeModule != null);
assert(nativeModule.ultimate() == 42);
But when I went to use it within electron.js, through the preload script, it returns in an error.
the preload script goes like this:
const {
contextBridge,
ipcRenderer
} = require("electron");
const nativeModule = require('./module.node');
const assert = require('assert');
assert(nativeModule.ultimate() == 42);
function pageLoaded()
{
// ...
}
window.addEventListener('DOMContentLoaded', pageLoaded);
the error when I attempt to load the module within electron application is:
A JavaScript error occured in the browser process
--------------------------- Uncaught Exception: Error: A dynamic link library (DLL) initialization routine failed.
\\?\C:\Users\001\Desktop\ele\module.node
at process.func [as dlopen] (VM70 asar_bundle.js:5)
at Object.Module._extensions..node (VM43 loader.js:1138)
at Object.func [as .node] (VM70 asar_bundle.js:5)
at Module.load (VM43 loader.js:935)
at Module._load (VM43 loader.js:776)
at Function.f._load (VM70 asar_bundle.js:5)
at Function.o._load (VM75 renderer_init.js:33)
at Module.require (VM43 loader.js:959)
at require (VM50 helpers.js:88)
at Object.<anonymous> (VM88 C:\Users\001\Desktop\ele\preload.js:6)
What's causing this and how do I fix this?
version
node version is: v14.17.0
electron.js: v13.1.1
both are 64-bit.
the module source code goes like this:
import std.stdio : stderr;
import node_dlang;
extern(C):
void atStart(napi_env env)
{
import std.stdio;
writeln ("Hello from D!");
}
int ultimate()
{
return 42;
}
mixin exportToJs! (ultimate, MainFunction!atStart);
it's compiled with dub command line. No arguments.
UPDATE 1 Do I need to rebuild this module? I found this but it didn't work for me either. I installed the electron-rebuild package by npm install --save-dev electron-rebuild and rebuild with .\node_modules\.bin\electron-rebuild.cmd -v 13.1.1 the command ran fine but I still got same error.
UPDATE 2: inside the console, I clicked in the javascript source code file link in the error message (from the exception) it points to this line of code, where there's this comment saying that:
no static exports found
what does that mean? is this related to the methods in D class? they're marked as public... not sure if related
Electron is a Windows-Application and therefore you need to remove output to std. Try to remove
import std.stdio : stderr;
and
import std.stdio;
writeln ("Hello from D!");
and retry import to Electron.
Please refer this (https://stackoverflow.com/a/74280836/9558119) post from me regarding same. Since it is electron build might be missing Visual C++ Build Environment: Visual Studio Build Tools

TypeError: Cannot read property 'compile' of undefined

I'm currently trying to follow this tutorial for Ethereum Solidity coding, and for the following code:
const path = require('path');
const fs = require('fs'); // File system module
const solc = require('solc').default; // Solidity Compiler module
// Note that phrase resolving a link means to substitute the actual location in the file system for the symbolic link
// If we assume that logFile is a symbolic link to dir/logs/HomeLogFile, then resolving it yields dir/logs/HomeLogFile
// Generates a path that points directly to the inbox file. __dirname will be the root direction
// inboxPath = desktop/inbox/contracts/inbox.sol
const inboxPath = path.resolve(__dirname, 'contracts', 'inbox.sol');
// The next step is to actually read the contents of the source file now
// utf8 is the encoding to read the file's content
const source = fs.readFileSync(inboxPath, 'utf8');
// Call solc.compile and pass in our source code, with only 1 contract
// console.log() means put the output in the console
console.log(solc.compile(source, 1));
I get the following error when I hover over const solc = require('solc').default:
Could not find a declaration file for module 'solc'. 'c:/Users/Hana PC/Desktop/inbox/node_modules/solc/index.js' implicitly has an 'any' type.
Try `npm i --save-dev #types/solc` if it exists or add a new declaration (.d.ts) file containing `declare module 'solc';`ts(7016)
When I try node compile.js, I get:
C:\Users\Hana PC\Desktop\inbox\compile.js:18
console.log(solc.compile(source, 1));
^
TypeError: Cannot read property 'compile' of undefined
at Object.<anonymous> (C:\Users\Hana PC\Desktop\inbox\compile.js:18:18)
[90m at Module._compile (internal/modules/cjs/loader.js:1063:30)[39m
[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)[39m
[90m at Module.load (internal/modules/cjs/loader.js:928:32)[39m
[90m at Function.Module._load (internal/modules/cjs/loader.js:769:14)[39m
[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)[39m
[90m at internal/main/run_main_module.js:17:47[39m
I've never used/interacted with TypeScript or JavaScript or anything of the sorts, so I honestly don't even know what this error means. I've already tried uninstalling and reinstalling solc multiple times, all to no avail.
My node.js version is:
6.14.8
I tried doing some searching online for what the implicitly has an 'any' type. means or how it could be fixed, but I honestly didn't get any of it. If it helps, my package.json looks like this:
{
"name": "inbox",
"version": "1.0.0",
"description": "",
"main": "compile.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"solc": "^0.8.0"
}
}
Any help is appreciated!
**** Update:**
Tried it with uninstall solc and a fresh install (without using version 0.4.17), and got an Assertion Error:
assert.js:383
throw err;
^
AssertionError [ERR_ASSERTION]: Invalid callback object specified.
at runWithCallbacks (C:\Users\Hana PC\Desktop\inbox\node_modules\[4msolc[24m\wrapper.js:97:7)
at compileStandard (C:\Users\Hana PC\Desktop\inbox\node_modules\[4msolc[24m\wrapper.js:207:14)
at Object.compileStandardWrapper [as compile] (C:\Users\Hana PC\Desktop\inbox\node_modules\[4msolc[24m\wrapper.js:214:14)
Wish I knew what was goin on
As per the discussion we had above, since the solidity file is using v0.4.17, you should use the same version of solc library in your code.
I have created a working example of your code here and the only two changes required were:
Making sure I use v0.4.17 of solc.
Import const solc = require("solc"); and not const solc = require("solc").default;
If you are having trouble downgrading the solc package, then
Delete package-lock.json file and node_modules/ folder.
Update the package.json files dependency to "solc": "0.4.17" and not to "^0.4.17"
Simply run npm install one last time.
This should be enough to get you up and running.

Why can't I eval a .load to start an interactive script in node.js?

In node.js you can pass the argument -i to get an interactive console, and then pass -e to evaluate a javascript statement.
I tried running:
$ node -i -e '.load ./someScript.js'
.load someScript.js;
^
SyntaxError: Unexpected token .
at Object.exports.runInThisContext (vm.js:53:16)
at Object.<anonymous> ([eval]-wrapper:6:22)
at Module._compile (module.js:410:26)
at node.js:578:27
at nextTickCallbackWith0Args (node.js:419:9)
at process._tickCallback (node.js:348:13)
And I get an error, but if I try to run the same thing from the interactive node prompt, it loads just fine; i.e.
> .load ./someScript.js
Is there something else I need to do to make this work?
Why can't I eval a .load to start an interactive script in node.js?
Because -e is for evaluating JavaScript code. The interactive REPL's commands aren't JavaScript, they're REPL interactive commands.
This question asks how to go interactive after running a script, which doesn't answer the "why" part (that's why I've posted the above), but its answers may give you some options for the somewhat-implied "...and what do I do instead?" part. :-)
You could maybe use a custom script to initiate the REPL from its module:
Something like:
const repl = require('repl'),
path = require('path'),
location = process.argv[2],
base = path.basename(location),
clean = path.split('.')[0];
const r = repl.start('> ');
Object.defineProperty(r.context, clean, {
configurable: false,
enumerable: true,
value: require(location)
});
So, now you can do node loadModule /path/to/load.js, the module will be available depending on the base of the path (/path/to/load.js will be available under load for example)

Gulp Node.js Istanbul Isparta

I'm trying to get unit tests coverage with Istanbul and Isparta, and I'm having some trouble.
Actually, here's my gulp file tasks:
gulp.task('pre-test', ['default'], function() {
return gulp.src('src/app/**/*.js')
.pipe(plumber())
.pipe(istanbul({
instrumenter: isparta.Instrumenter,
includeUntested: true
}))
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['pre-test'], function() {
return gulp.src('src/test/**/*.js')
.pipe(mocha({reporter: 'spec'}))
.pipe(istanbul.writeReports({}));
});
When I start the gulp "test" task, I have the following errors:
[08:34:17] Plumber found unhandled error:
Error in plugin 'gulp-istanbul'
Message:
Unable to parse C:\projects\nodejs\mon-notaire\src\app\core\logger\concrete\ConsoleLogger.js
Line 1: Unexpected token
[08:34:17] Finished 'pre-test' after 2.11 s
[08:34:17] Starting 'test'...
stream.js:94
throw er; // Unhandled stream error in pipe.
^
C:\projects\nodejs\mon-notaire\src\test\core\TestConfReader.js:1
(function (exports, require, module, __filename, __dirname) { import ConfReade
^^^^^^
SyntaxError: Unexpected reserved word
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Object.Module._extensions.(anonymous function) [as .js] (C:\projects\nodejs\mon-notaire\node_modules\gulp-istanbul\node_modules\istanbul\lib\hook.js:109:37)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at C:\projects\nodejs\mon-notaire\node_modules\mocha\lib\mocha.js:192:27
at Array.forEach (native)
npm ERR! Test failed. See above for more details.
How can I prevent these errors from occurring?
Have you set up .babelrc?
If you're using the latest version of isparta, which depends on babel v6, then you need to set up .babelrc like the following. ( You also need to do npm install --save-dev babel-preset-es2015 )
{
"presets": [
"es2015"
]
}
From gulp-istanbul github page.
var isparta = require('isparta');
var istanbul = require('gulp-istanbul');
gulp.src('lib/**.js')
.pipe(istanbul({
// supports es6
instrumenter: isparta.Instrumenter
}));
This line :
Message:
Unable to parse C:\projects\nodejs\mon-notaire\src\app\core\logger\concrete\ConsoleLogger.js
Means that there is a problem in your code in ConsoleLogger.js , so you might want to check that file out.
This Line :
C:\projects\nodejs\mon-notaire\src\test\core\TestConfReader.js:1
(function (exports, require, module, __filename, __dirname) { import ConfReade
^^^^^^
SyntaxError: Unexpected reserved word
Suggests that you are using ES6, but your gulp task is not transpiling it to ES5 before running it, which is why you are getting the error.
I have made a yeoman generator which creates a project for exactly this purpose (writing nodeJs projects in ES6) and includes code coverage using istanbul with source code mapping. You might want to take a look at that.
Otherwise, here is my working gulpfile from that generator.
I use istanbul, along with a module called remap-istanbul.
The error message indicates that you are using ES6, but the gulp-istanbul doesn't support it by default.
Of course, you can write your functions to compile the ES6 codes, but considering you are using gulp in this case, IMHO the simplest way you can do is to use gulp-babel-istanbul instead of gulp-istanbul, no need to change your code attached above at all.
import istanbul from 'gulp-babel-istanbul'
And the rest of the code remains the same.

command line node.js; running script with modules

I'm doing some testing with node.js and several modules\libraries. For simplicity I'll focus on underscore.js.
When I run node.exe with the following source:
require("./underscore.js");
_.each({one : 1, two : 2, three : 3}, function(num, key){ console.log(num); });
I get:
C:\Dropbox\personal-work\foo\test code>node library-tests.js
node.js:208
throw e; // process.nextTick error, or 'error' event on first tick
^
ReferenceError: _ is not defined
at Object.<anonymous> (C:\Dropbox\personal-work\foo\test code\library-tests.js:2:1)
at Module._compile (module.js:425:26)
at Object..js (module.js:443:10)
at Module.load (module.js:344:31)
at Function._load (module.js:303:12)
at Array.<anonymous> (module.js:463:10)
at EventEmitter._tickCallback (node.js:200:26)
What is also strange is that when I run it like this:
node underscore.js library-tests.js
It doesn't seem to do anything at all...I've even added log statements, they don't seem to execute.
I've also tried pasting in the underscore.js source into the top of my source and I get the same error...
Does anyone know what I'm doing wrong here? Thanks.
try assigning it:
var _ = require('../underscore.js');
You can see here in the annotated source code that underscore will not add itself to the global namespace if it is running in a CommonJS implementation (of which, Node.JS is one).

Categories

Resources