I'm running Meteor 1.4.2.3 and after adding some code that deals with files I get a reference error saying "Buffer" is not defined.
The error is in util.js
exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer;
Uncaught ReferenceError: Buffer is not defined
at util.js (modules.js:29525)
at fileEvaluate (modules-runtime.js:343)
at require (modules-runtime.js:238)
at meteorInstall.node_modules.meteor-node-stubs.node_modules.readable-stream.lib._stream_readable.js (modules.js:25209)
at fileEvaluate (modules-runtime.js:343)
at require (modules-runtime.js:238)
at meteorInstall.node_modules.meteor-node-stubs.node_modules.readable-stream.readable.js (modules.js:25144)
at fileEvaluate (modules-runtime.js:343)
at require (modules-runtime.js:238)
at meteorInstall.node_modules.meteor-node-stubs.node_modules.stream-browserify.index.js (modules.js:24653)
at fileEvaluate (modules-runtime.js:343)
at require (modules-runtime.js:238)
at meteorInstall.node_modules.gm.index.js (modules.js:21644)
at fileEvaluate (modules-runtime.js:343)
at require (modules-runtime.js:238)
at meteorInstall.both.collections.files.collection.js (app.js:2317)
at fileEvaluate (modules-runtime.js:343)
at require (modules-runtime.js:238)
at app.js:2583
What is the dependency for Buffer ? am I missing a package?
Buffer is a builtin class in Node.js and doesn't exist in browsers. If there is a separate browser compatible version of the dependency try using that one instead. If not, there is a package in NPM called buffer that can be used as a polyfill in browsers, React Native and other non-Node.js environments.
import Buffer from 'buffer';
if (typeof this.Buffer === 'undefined') {
this.Buffer = Buffer.Buffer;
}
Adding this code on Startup worked for me
global.Buffer = function() {}
global.Buffer.isBuffer = () => false
Complete Code looks like this
Meteor.startup(()=> {
global.Buffer = function() {}
global.Buffer.isBuffer = () => false
ReactDOM.render(<App />, document.getElementById('container'));
});
Related
What I'm actually doing is writing a VS Code Extension, but since I'm new to Node I'm struggling with referencing one JS file from another.
//main.js (compiled from TypeScript)
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("./Test.js");
console.log("hello");
t1();
and
//Test.js
function t1() {
console.log("t1");
}
They're both in the same folder. If I run it from VS Code, or from node directly, it doesn't work
PS E:\VSCodeTest> node src/main.js
hello
E:\VSCodeTest\src\main.js:5
t1();
^
ReferenceError: t1 is not defined
at Object.<anonymous> (E:\VSCodeTest\src\main.js:5:1)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
The VS Code project is actually TypeScript but I've distilled it down to the crux of the problem in the JS files.
I believe it should work based on
https://www.typescriptlang.org/docs/handbook/modules.html
Import a module for side-effects only Though not recommended practice,
some modules set up some global state that can be used by other
modules. These modules may not have any exports, or the consumer is
not interested in any of their exports. To import these modules, use:
import "./my-module.js";
How have I misunderstood that?
Change Test.js to this:
//Test.js
function t1() {
console.log("t1");
}
module.exports = t1;
And then do something more like this in main.js:
const t1 = require("./Test.js");
t1(); // prints "t1"
There's a lot of information about how modules work in the docs: https://nodejs.org/api/modules.html
Alternatively, if you want t1 to be a global, then assign it to global.t1 in Test.js:
//Test.js
global.t1 = function t1() {
console.log("t1");
};
I wouldn't recommend that if you can avoid it, though, for all the reasons people recommend avoiding globals when possible
Require doesn't work quite like that, but you're close -- if you want to use a function you've created to in another file, just add it to that file's exports.
/// test.js
exports.t1 = function() ...
// or
module.exports = {
t1: function() ...
}
Then you need to specifically save that off to use it
/// main.js
var t1 = require('./test.js').t1;
t1();
Global scoping doesn't work like it does in the browser, check out node's docs on it, or try a blog explaining it (I didn't write this and can't fully vouch)
I have google.profobuf.* imports in a proto file (used by GRPC server written in go). When the same proto file is used to implement a GRPC client in NodeJS - I run into issues.
Details:
proto file used by the GRPC server (written in go):
tech.proto
syntax = "proto3";
package api;
import "google/protobuf/duration.proto";
import "google/protobuf/empty.proto";
message Info {
string desc = 1;
google.protobuf.Duration ttl = 2;
}
service Tech {
rpc BasicInfo(google.protobuf.Empty) returns (Info) {}
}
When this is used by the GRPC client written in NodeJs:
getTechInfo.js (first few lines)
'use strict';
const PROTO_PATH = __dirname + '/../../api/tech.proto';
const grpc = require('grpc');
const apiProto = grpc.load(PROTO_PATH).api;
I get the following error:
/Users/././node_modules/protobufjs/dist/protobuf.js:4720
throw Error("failed to import '"+importFilename+"' in '"+filename+"': file not found");
^
Error: failed to import '/Users/././api/google/protobuf/duration.proto' in '/Users/././api/register.proto': file not found
at Builder.ProtoBuf.Builder.BuilderPrototype.import (/Users/././node_modules/protobufjs/dist/protobuf.js:4720:35)
at Object.ProtoBuf.loadJson (/Users/././node_modules/protobufjs/dist/protobuf.js:5225:26)
at Object.ProtoBuf.loadProto (/Users/././node_modules/protobufjs/dist/protobuf.js:5128:25)
at Object.ProtoBuf.loadProtoFile (/Users/././node_modules/protobufjs/dist/protobuf.js:5174:52)
at Object.load (/Users/././node_modules/grpc/index.js:135:26)
at Object.<anonymous> (/Users/././src/api/getTechInfo.js:5:23)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
The issue is with the imports in the proto file:
import "google/protobuf/duration.proto";
import "google/protobuf/empty.proto";
What is the recommended method to resolve these imports? Thanks in advance.
Using:
Node v8.9.4
"google-protobuf": "^3.5.0",
"grpc": "^1.10.1",
This is a known issue with the gRPC library, documented primarily in this issue. The grpc.load API does not support easily loading google/protobuf/*.proto files.
The simplest solution is to use the #grpc/proto-loader library, which automatically includes google/protobuf/*.proto files when loading proto files.
One alternative solution is to use grpc-tools to pre-generate files that can be used with the google-protobuf library.
I am setting up a brand new project in Express using Babel and ESLint, and am trying to setup dynamic routes. The only issue is that I cannot figure out how to call the loader for the routes. This is my current code regarding the loader.
routes/index.js
import fs from 'fs';
/**
* Register Default Routes
* #param {Object} app express.Application
*/
export default function(app) {
fs.readdirSync(__dirname).forEach((fileName) => {
if (fileName == __filename.slice(__dirname.length + 1)) return;
let fileNameStripped = fileName.substring(0, fileName.lastIndexOf('.'));
require('./' + fileNameStripped)(app); // does not work
});
}
index.js
import express from 'express';
import routes from './routes/index.js';
const app = express();
app.use(express.static('public'));
routes(app); // works now
...
Babel Error
TypeError: require(...) is not a function
at /app/build/routes/index.js:1:314
at Array.forEach (<anonymous>)
at exports.default (/app/build/routes/index.js:1:195)
at Object.<anonymous> (/app/build/index.js:1:393)
at Module._compile (module.js:649:30)
at Object.Module._extensions..js (module.js:660:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:501:12)
at Function.Module._load (module.js:493:3)
at Function.Module.runMain (module.js:690:10)
The issue appears to be related to https://github.com/babel/babel/issues/2683
Since nested route files are supposed to be ES modules with default exports, require('./' + fileNameStripped) is module object and not a function. It should be:
require('./' + fileNameStripped).default(app);
Depending on Babel configuration (dynamic-import-node plugin is required), require() can be replaced with dynamic import() but it's less desirable here, because dynamic import is not synchronous and can cause race conditions.
I am working on a Sails.js project that requires me to use this NPM package. I created a new Sails.js service to invoke this package after npm install-ing it like this:
// Require and initialize the rules engine
var jsonRulesEngine = require('json-rules-engine'),
rulesEngine = new jsonRulesEngine();
When I run this script, I get the following error:
/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/async.js:61
fn = function () { throw arg; };
^
TypeError: jsonRulesEngine is not a constructor
at Object.verify (/Users/Nag/Code/learn-nodejs/server/api/services/RulesService.js:21:27)
at Object.wrapper [as verify] (/Users/Nag/Code/learn-nodejs/server/node_modules/#sailshq/lodash/lib/index.js:3250:19)
at /Users/Nag/Code/learn-nodejs/server/api/controllers/UtilsController.js:113:43
at /Users/Nag/Code/learn-nodejs/server/api/services/RedisService.js:55:13
at tryCatcher (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/util.js:16:23)
at Promise.successAdapter [as _fulfillmentHandler0] (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/nodeify.js:23:30)
at Promise._settlePromise (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/promise.js:566:21)
at Promise._settlePromise0 (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/promise.js:693:18)
at Async._drainQueue (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/async.js:17:14)
at Immediate.<anonymous> (/Users/Nag/Code/learn-nodejs/server/node_modules/async-listener/glue.js:188:31)
at runCallback (timers.js:666:20)
at tryOnImmediate (timers.js:639:5)
at processImmediate [as _immediateCallback] (timers.js:611:5)
[nodemon] app crashed - waiting for file changes before starting...
Any clue why I might get that error? In the examples section of the package, the owner of the package imports the package using ES6 format whereas I am requiring it. Does that make a difference?
When you require an NPM package, depending on your module system1, the default export will not automatically be imported when you do this:
var jsonRulesEngine = require('json-rules-engine');
So when you require like you did, it will return the module object, not necessarily the default export as expected. In the package json-rules-package the Engine is exported by default but your require doesn't require the default. If you log the returned module object it will look like this:
{
Engine: function(...) { ... },
Fact: function(...) { ... },
Operator: function(...) { ... },
Rule: function(...) { ... },
default: function(...) { ... }
}
The engine is under the property default and Engine. You could do:
var jsonRulesEngine = require('json-rules-engine').default();
Or:
var jsonRulesEngine = require('json-rules-engine').Engine;
The first will explicitly import the default export. Then you can create an instance of the class like so:
var rulesEngine = new jsonRulesEngine();
1 Yes, using ES2015 import will affect the outcome. If you were to use import syntax from ES2015, this problem would not be encountered. To know why see this answer. In short, Babel transpiles ES2015 code so that default is explicitly accessed when requiring thus importing the default export.
When I try to launch my app in electron shell I get the below error:
I'm using node v0.12.3
I have installed electron-prebuilt
Uncaught Exception:
Error: Module version mismatch. Expected 43, got 14.
at Error (native)
at Object.module.(anonymous function) (ATOM_SHELL_ASAR.js:118:20)
at Object.module.(anonymous function) [as .node] (ATOM_SHELL_ASAR.js:118:20)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:298:12)
at Module.require (module.js:353:17)
at require (module.js:372:17)
at bindings (/src/git/superqa/node_modules/bcrypt/node_modules/bindings/bindings.js:76:44)
at Object.<anonymous> (/src/git/superqa/node_modules/bcrypt/bcrypt.js:3:35)
at Module._compile (module.js:418:26)
// my main.js file looks like this superqa/main.js
var app = require("./app/app.js");
var App = require("./src/app.js");
new App(app);
//my src/app.js looks like this superqa/src/app.js
var path = require("path");
var BrowserWindow = require('browser-window');
module.exports = App;
function App(app) {
var self = this;
this._app = app;
this._assetDir = path.resolve(__dirname, "..", "dist");
this.mainWindow = null;
app.on('ready', function() {
self.mainWindow = new BrowserWindow({
width: 1024,
height: 768
});
self.mainWindow.loadUrl("http://localhost:3000/login");
});
}
The problem is that the pre-built binaries were built with io.js 1.x, which uses a different (higher) ABI version than node.js. So if you want to use the pre-built version, you have to use io.js 1.x. Otherwise you will have to build electron yourself if you want to keep using node 0.12.x.