Problems at require(<Module>) in self written Node-RED node - javascript

I added a self written WebSocket-Client library. When I require in node.js it works fine, just as in Node-RED's function-node with registering it in settings.js and requireing it by global.get("RWSjs").
Now I had to write a Node by myself and wanted to require this file, and it doesn't work. Node-RED always gives me the "node not deployed" error, which is, I think, because of a javascript syntax error.
How can I require a self written module in a self written node's .js?
Thanks a lot in advance, Peter :)
Edit:
some Code:
eval-R-char.js (Code for the node)
module.exports = function(RED) {
// doesn't work:
var RWSjs = global.get("RWSjs");
function EvalRCharNode(config) {
RED.nodes.createNode(this,config);
this.instruction = config.instruction;
var node = this;
this.on('input', function(msg) {
//msg.payload = msg.payload.toLowerCase();
msg.payload = "Instruction: " + this.instruction;
node.send(msg);
});
}
RED.nodes.registerType("eval-R-char",EvalRCharNode);
}

You shouldn't use the context to require modules when writing your own nodes, it is purely a workaround as you can't use require in the function node.
You should just require as normal in your custom node.
So in this case:
module.exports = function(RED) {
//assuming your module is in the RWS.js file in the same directory
var RWSjs = require('./RWS.js');
function EvalRCharNode(config) {
RED.nodes.createNode(this,config);
this.instruction = config.instruction;
var node = this;
this.on('input', function(msg) {
//msg.payload = msg.payload.toLowerCase();
msg.payload = "Instruction: " + this.instruction;
node.send(msg);
});
}
RED.nodes.registerType("eval-R-char",EvalRCharNode);
}

Related

Require in require javascript

I made a nice folder structure with the use of require and require in require in javascript. As the require in require needs all functions to be included again I was wondering if there are easier ways to do this.
var file2 = require('./file2.js');
var IncludeAll={
func1: function(msg){
return file2.function1(msg);
},
func2: function(msg){
return file2.function2(msg);
}
};
module.exports = IncludeAll;
You can create a exporter script "exporter.js" file like below.
// exporter.js
module.exports = {
File2: require('./file2'),
File3: require('./file3')
}
Then you can import and call like this.
const {File2} = require('./exporter')
const param = 5;
File2.func1(param);
File2.func2(param);

Syncing files from one directory to another in Node?

I was using cpy with a globbing pattern to find and copy all the files in src/main/css and place them in ./dist.
However now I also have sub directories below src/main/css (For example src/main/css/margins/index.css) and cpy does not include these when copying the files.
Is there an API in Node (fs or path?) that handles this case, or anyone know of a handy package?
Try this.
const fs = require('fs');
const path = require('path');
var mkdir = function (dir) {
// making directory without exception if exists
try {
fs.mkdirSync(dir, 0755);
} catch (e) {
if (e.code != "EEXIST") {
throw e;
}
}
};
var copy = function (src, dest) {
var readS = fs.createReadStream(src);
var writeS = fs.createWriteStream(dest);
readS.pipe(writeS);
readS.on("end", function () {
// Operation done
});
};
var copyDir = function (src, dest) {
mkdir(dest);
var files = fs.readdirSync(src);
for (var i = 0; i < files.length; i++) {
var current = fs.lstatSync(path.join(src, files[i]));
if (current.isDirectory()) {
copyDir(path.join(src, files[i]), path.join(dest, files[i]));
} else if (current.isSymbolicLink()) {
var symlink = fs.readlinkSync(path.join(src, files[i]));
fs.symlinkSync(symlink, path.join(dest, files[i]));
} else {
copy(path.join(src, files[i]), path.join(dest, files[i]));
}
}
};
copyDir('./src', './dest');
This piece of code is inspired from https://gist.github.com/tkihira/3014700. I have made some modifications in the original code to get it working as util.pump is obsolete now.
I ended up using using copy-dir
require('copy-dir').sync(PLI.src.main.css, PLI.DIST);
If anyone has a way to do the same thing with the Node and avoiding dependencies please do tell.

Accessing typescript file variable values using gulp

I have several typescript files, some of them export a const named APIS.
I'm trying to access those exports (I want to concatenated all of them to a single file), but it doesn't seem to work. I'm obviously doing something wrong, but I'm not sure what.
For example, I have a folder named services, with 2 files: service1.ts, service2.ts.
service1.ts:
...
export const APIS = [ { "field1" : "blabla" } ];
service2.ts: does not contain the APIS var.
This is my gulpfile.js:
var gulp = require('gulp');
var concat = require('gulp-concat');
var map = require('gulp-map');
gulp.task('default', function() {
return gulp.src('.../services/*.ts')
.pipe(map(function(file) {
return file.APIS;
}))
.pipe(concat('all.js'))
.pipe(gulp.dest('./test/'));
});
When I run this task, I get nothing. When I added console.log(file.APIS); to the map function, I get undefined for all the values (although it is defined in service1.ts!).
This is following to: Extracting typescript exports to json file using gulp
EDIT: OK, so I tried saving the exports in a .js file instead of a .ts file, and now I can access those vars using require:
gulp.task('default', function() {
return gulp.src('./**/*.service.export.js')
.pipe(map(function(file) {
var fileObj = require(file.path);
...
}))
Now if I try console.log(fileObj.APIS); I get the correct values. What I'm still confused about is how I can pass these value on, and create a single file out of all these vars. Is it possible to push them into an array?
This will not work as you think it would work. Gulp itself knows nothing about typescript files, that file is a vinyl-file and has no knowledge about the typescript code within its content.
Edit
Based on your example, you can do something like this:
var gulp = require('gulp');
var concat = require('gulp-concat');
var map = require('gulp-map');
var fs = require('fs');
gulp.task('test', function ()
{
var allConstants = [];
var stream = gulp.src('./**/*.service.export.js')
.pipe(map(function(file)
{
var obj = require(file.path);
if (obj.APIS != null)
allConstants = allConstants.concat(obj.APIS);
return file;
}));
stream.on("end", function (cb)
{
// Do your own formatting here
var content = allConstants.map(function (constants)
{
return Object.keys(constants).reduce(function (aggregatedString, key)
{
return aggregatedString + key + " : " + constants[key];
}, "");
}).join(", ");
fs.writeFile('filename.txt', content, cb);
});
return stream;
});
Suggestion
If you want to collect multiple variables into a single file i.e. a common variables file I suggest gulp-replace.
Steps
Create a file, require it and use tags within that file to place your variables.
Advice
If you are already using services don't create an array. Instead create an object (JSON) where every property is a constant. i.e.
var constants = {
const_1: 0,
const_2: 1,
const_3: 2,
}

Typeerror when including a module in node.js

I'm following the nodeschool learnyounode tutorial and I'm having some trouble with the module lesson. In short I'm supposed to make a module which I pass a directory to and a file extension and then use a callback to print the list of files with that extension in the folder.
I have two files, my module (mymodule.js):
var module = require('module');
var fs = require('fs');
var path = require('path');
module.exports = function(testDirectory, testExtension, callback)
{
fs.readdir(testDirectory, function(error, folderContents)
{
if (error) return callback(error);
for (i = 0; i < folderContents.length; i++)
{
var fileExtension = path.extname(folderContents[i]);
if(fileExtension === "." + testExtension)
{
callback(null, folderContents[i]);
}
}
});
};
and my app file (program.js):
var mymodule = require('./mymodule.js');
mymodule(process.argv[2], process.argv[3], function(error, data)
{
console.log(data);
});
Whenever I try test my app file, I get TypeError: mymodule is not a function
I've done lots of reading, but the more I read the more confused I become. Someone please help?

iterate through directory with Assets.getText

In meteor I can read a file like this:
myjson = JSON.parse(Assets.getText("lib/myfile.json"))
Now i want to iterate through a folder, and read all the available json files. What would be the best way to do this without installing extra NPM packages.
Thank you for your time.
I'm not sure if this is the best way, but is certainly an easy one:
var fs = Npm.require('fs');
fs.readdir('./assets/app/myFolder', function(e, r) {
_.each(r, function(filename) {
Assets.getText('myFolder/' + filename);
});
});
I wrapped Hubert OGs code into a function with Meteor.bindEnvironment. I believe this is necessary because of fibre not available outside of the Meteor environement.
see https://www.eventedmind.com/feed/49CkbYeyKoa7MyH5R
Beware that external Node packages have different document root than Meteor.
var done, files;
var fs = Npm.require('fs');
files = fs.readdirSync("../../../../../server/collections/lib/", function(e, r) {});
done = Meteor.bindEnvironment(function(files) {
return _.each(files, function(filename) {
var myjson;
myjson = JSON.parse(Assets.getText("lib/" + filename));
/* do Something */
});
}, function(e) {
throw e;
});
done(files);

Categories