How to inject variable value into JS file from GULP - javascript

Hopefully this is a quick question.
What I'm trying to do is to add a timestamp into a Javascript object in a JS file while the file is being built with GULP. Basically, in "file.js", I have an object where I would like to have object.timeStamp that equals the time of the GULP build.
I am currently adding a timestamp to the top of the file using gulp-header, but I have been asked to add the timestamp to a property in the object.
My thought was to inject the value from GULP, but all of the injection plugins I have found so far are for injecting contents of one file into the target file.
Any help would be greatly appreciated.

Are you using any kind of modules? ES6 modules, AMD, CommonJS, ...?
If so, you can generate a config module with Gulp where you can inject any variable you want. It would look something like this:
config.tmpl.js
module.exports = <%= config %>
config gulp task
var gulp = require('gulp');
var template = require('gulp-template');
var rename = require('gulp-rename');
gulp.task('config', function() {
return gulp.src('path/to/config.tmpl.js')
.pipe(template({config: JSON.stringify({
timeStamp: new Date()
})}))
.pipe(rename('config.js'))
.pipe(gulp.dest('path/to/config.js'));
});
and finally, in your JS file
var config = require('path/to/config.js');
var object = {
timeStamp: config.timeStamp
}

O.K., so I figured out a workaround that gets me where I want to be. The first this is using the gulp-header to insert a variable declaration into my Javascript file using this code:
In GULP:
var d = new Date();
.pipe(header("var timeStamp = '" + d +"';"))
Then, in my Javascript file, I set up a property in the object that is a function, and sets the timeStamp property I was looking for by getting the value from the timeStamp variable injected above using the gulp-header, like this:
In the JS File, the header functionality inserts this:
var timeStamp = 'Tue Dec 08 2015 15:15:11 GMT-0800 (PST)';
And then my function, in the JS Object is simply this:
ts: function(){
object.timeStamp = timeStamp;
},
Which, when called, runs and sets the timestamp inside of the object.
It seems like there should be an easier way to do this, but for now, this is working.
If you have any ideas on making it better, I would love to hear them!

Related

Importing an external library into nodejs vm

I am developing a nodejs library that allows for the user to write their own JS code which will be executed. For example:
var MyJournal = Yurnell.newJournal();
module.exports = function(deployer) {
MyJournal.description = "my first description"
// deployment steps
deployer.deploy(MyJournal)
};
This eventually gets called using nodejs VM
var script = vm.createScript(fileWithFrontend.content, file);
script.runInNewContext(context);
Passing in the Yurnell and deployer object via the context parameter.
My question is whether there is a way for the user to also import their own libraries into the script? and if so where in users path would the script look for the library?
For example in their code it would be useful for them to do something like var moment = require('moment'); and format the dates using that library also.
Thanks
you can use node:VM linker
for a detailed explanation - https://nodejs.org/api/vm.html#modulelinklinker

node.js dynamic module(file) export

how can I exports this dynamic module?
// ./data/example5.js
module.exports = {title : example5, recentCheck : "2018-08-22"}
The contents change in real time. And I execute the followed function once a minute and connect the module.
var files = fs.readdirSync(`./data/`);
var i = 0;
var link = [];
while(i<files.length){ // read all file
link[i] = require(`../data/${files[i]}`);
 
//main.js
setInterval(start,10000);
I try to create and connect a new module file once a minute, but the first stored file(module) is extracted. The modulefile is being saved in real time correctly.
Shutting down and running the node will extract the changed modules correctly.
How do I handle a dynamically changing module?
I would recommend saving the data in a JSON file and then reading the data from the file rather than trying to use it as a module.
Just make the objects you're updating variables in the module that you're including.
Make a function called getVariable, and simply return the variable.
Include getVariable in your main module.

How do you modify a nodejs module variable?

(This is probably a very silly question since I'm just beginning with nodejs, nevertheless I can't understand how this works. Let me know what is missing in my question, I'll correct.)
I'm trying to use the npm package likely.
in my server.js file I have thus written this
var Recommender = require('likely');
in likely.js you can find variables like these:
var DESCENT_STEPS = 5000; // number of iterations to execute gradient descent
var ALPHA = 0.0005; // learning rate, should be small
I would like to modify these variables inside my server.js file.
I believe the way to do that is adding this after the require()
Recommender.DESCENT_STEPS = 9999999999;
but that doesn't seem to change the value that is defined in likely.js and that is actually used by the model. (by running the model I can see it doesn't work since so much steps should take forever and the processing time doesn't change at all)
Can I only do this by modifying likely.js?
You cannot modify them programmatically because likely.js only uses the local variable values instead of the current value of the exported versions of the same variables. So if you wanted to change those values you currently would need to edit likely.js. You might want to submit a pull request to that project's repository that makes the code use the exported value (e.g. module.exports.DESCENT_STEPS) instead.
You need to publicize these variables to be viewable by server.js.
var object = {
DESCENT_STEPS = 5000;
ALPHA = 0.0005;
}
module.exports = object;
Now it can be viewed and modified in server.js.
Recommender.ALPHA = 'new value';

NodeJS & Gulp Streams & Vinyl File Objects- Gulp Wrapper for NPM package producing incorrect output

Goal
I am currently trying to write a Gulp wrapper for NPM Flat that can be easily used in Gulp tasks. I feel this would be useful to the Node community and also accomplish my goal. The repository is here for everyone to view , contribute to, play with and pull request. I am attempting to make flattened (using dot notation) copies of multiple JSON files. I then want to copy them to the same folder and just modify the file extension to go from *.json to *.flat.json.
My problem
The results I am getting back in my JSON files look like vinyl-files or byte code. For example, I expect output like
"views.login.usernamepassword.login.text": "Login", but I am getting something like {"0":123,"1":13,"2":10,"3":9,"4":34,"5":100,"6":105 ...etc
My approach
I am brand new to developing Gulp tasks and node modules, so definitely keep your eyes out for fundamentally wrong things.
The repository will be the most up to date code, but I'll also try to keep the question up to date with it too.
Gulp-Task File
var gulp = require('gulp'),
plugins = require('gulp-load-plugins')({camelize: true});
var gulpFlat = require('gulp-flat');
var gulpRename = require('gulp-rename');
var flatten = require('flat');
gulp.task('language:file:flatten', function () {
return gulp.src(gulp.files.lang_file_src)
.pipe(gulpFlat())
.pipe(gulpRename( function (path){
path.extname = '.flat.json'
}))
.pipe(gulp.dest("App/Languages"));
});
Node module's index.js (A.k.a what I hope becomes gulp-flat)
var through = require('through2');
var gutil = require('gulp-util');
var flatten = require('flat');
var PluginError = gutil.PluginError;
// consts
const PLUGIN_NAME = 'gulp-flat';
// plugin level function (dealing with files)
function flattenGulp() {
// creating a stream through which each file will pass
var stream = through.obj(function(file, enc, cb) {
if (file.isBuffer()) {
//FIXME: I believe this is the problem line!!
var flatJSON = new Buffer(JSON.stringify(
flatten(file.contents)));
file.contents = flatJSON;
}
if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Streams not supported! NYI'));
return cb();
}
// make sure the file goes through the next gulp plugin
this.push(file);
// tell the stream engine that we are done with this file
cb();
});
// returning the file stream
return stream;
}
// exporting the plugin main function
module.exports = flattenGulp;
Resources
https://github.com/gulpjs/gulp/blob/master/docs/writing-a-plugin/README.md
https://github.com/gulpjs/gulp/blob/master/docs/writing-a-plugin/using-buffers.md
https://github.com/substack/stream-handbook
You are right about where the error is. The fix is simple. You just need to parse file.contents, since the flatten function operates on an object, not on a Buffer.
...
var flatJSON = new Buffer(JSON.stringify(
flatten(JSON.parse(file.contents))));
file.contents = flatJSON;
...
That should fix your problem.
And since you are new to the Gulp plugin thing, I hope you don't mind if I make a suggestion. You might want to consider giving your users the option to prettify the JSON output. To do so, just have your main function accept an options object, and then you can do something like this:
...
var flatJson = flatten(JSON.parse(file.contents));
var jsonString = JSON.stringify(flatJson, null, options.pretty ? 2 : null);
file.contents = new Buffer(jsonString);
...
You might find that the options object comes in useful for other things, if you plan to expand on your plugin in future.
Feel free to have a look at the repository for a plugin I wrote called gulp-transform. I am happy to answer any questions about it. (For example, I could give you some guidance on implementing the streaming-mode version of your plugin if you would like).
Update
I decided to take you up on your invitation for contributions. You can view my fork here and the issue I opened up here. You're welcome to use as much or as little as you like, and in case you really like it, I can always submit a pull request. Hopefully it gives you some ideas at least.
Thank you for getting this project going.

node.js log module bunyan change timezone

I'm using this logging module bunyan.js which is included in the framwork restify.js. The module does outprint a time in the log file/console, however, I want to change the time to UTC/GMT, not sure if it's possible wihtout modifying the module code?
If you don't want to use local time anywhere else in your process, one way to achieve what you want is to change the timezone for the process. Either by writing this statement at the startup of you application:
process.env.TZ = 'UTC'
Or by starting it with a environment variable from the command line, like this:
TZ=UTC node main.js
I was also facing the same issue and resolved it by adding a custom attribute, localtime, while creating the logger using bunyan.createLogger method like this:
var init = function () {
log = bunyan.createLogger({
name: 'myLogs',
src: true,
localtime: new Date().toString();
});
};
By doing this, I get an extra field in my log called localtime with the appropriate time as per my timezone.
Hope this helps.

Categories

Resources