jsRender and node.js - node.js

I am a complete beginner with node.js.
What I try to do is to parse a jsrender template on server side
I donwloaded jsrender.js from git
this is my attempt ... saved as render.js:
var data = [
{id:1, name:"tom"},
{id:2, name:"jack"},
]
require('./jsrender.js', function(jsrender){
console.log('test');
var result = jsrender.render['<p>{{:id}} <b>{{:name}}</p>']( data );
console.log(result);
} );
and then runned it (node render.js)
and I get NOTHING
what am I doing wrong?
======================================================
tried this way too:
var data = [
{id:1, name:"tom"},
{id:2, name:"jack"},
]
var jsrender = require('./jsrender.js');
var result = jsrender.render('<p>{{:id}} <b>{{:name}}</p>',data );
console.log(result);
and I am getting
var result = jsrender.render('<p>{{:id}} <b>{{:name}}</p>',data );
^
TypeError: Object #<Object> has no method 'render'
========================================================================
tried also installing this node_jsrender module
and this syntax:
var jsrender = require('./jsrender');
process.on('start', function () {
jsrender.template("yourtemplate", "{{:myvar}}");
var result = jsrender.render("yourtemplate", {myvar:"Hello World!"});
console.log(result);
});
ALSO EMPTY result :(

So first you need to install the Node.js module.
npm install node_jsrender
This will create a node_modules directory with node_jsrender directory inside. Next you need to require.
var jsrender = require('node_jsrender');
If the first parameters of the require method starts with ./ it means that you want to import a local file. Without it Node.js will look at the node_modules directory.
jsrender.template("yourtemplate", "{{=myvar}}");
var result = jsrender.render("yourtemplate", {myvar:"Hello World!"});
I checked the syntax of that template engine and it's {{= and not {{:?

Related

Reuseable configuration file for gulp

I want to ask a question about importing js file into another js file and use it in gulp. You can see my gulp.config file and gulpfile. when i try to run gulp task which is vet i am getting error like this ;
[00:06:21] Using gulpfile ~\pluralsight-gulp-master\gulpfile.js
[00:06:21] Starting 'vet'...
[00:06:21] 'vet' errored after 13 ms
[00:06:21] Error: Invalid glob argument: undefined
at Gulp.src (C:\Users\Altan\pluralsight-gulp-master\node_modules\vinyl-fs\li
b\src\index.js:20:11)
gulp.config.js
module.exports = function(){
var config = {
//all js to vet
alljs: [
'./src/**/*.js',
'./*.js'
]
};
return config;
};
gulpfile.js
var gulp = require ('gulp');
var jscs = require ('gulp-jscs');
var jshint = require ('gulp-jshint');
var util = require ('gulp-util');
var gulpprint = require ('gulp-print').default;
var gulpif = require ('gulp-if');
var args = require ('yargs').argv;
var config= require('./gulp.config');
gulp.task('vet',done=>{
gulp
.src(config.alljs)
.pipe(gulpif(args.verbose,gulpprint()))
.pipe(gulpprint())
.pipe(jscs())
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish',{verbose:true}));
done();
});
you are returning a function from gulp.config.js
when you require it, it should be
require('./gulp.config')()

Custom module in Node.js

I am new to NodeJS programming so I was trying make simple custom module by extending one module to another which prints in console log.
ExtendMod.js
var exports = module.exports = {};
exports.tutorial = function() {
console.log("N Tutotial");
}
app.js
var Tutor=require('./ExtendMod.js');
exports.NodeTutorial = function() {
console.log("Node Tutorial")
function pTutor() {
var PTutor=Tutor
PTutor.tutorial;
}
}
console.log(require('./thirdNode.js').NodeTutorial());
I have extended ExtendMod.js in app.js.
Question: Why an empty braces after exports when we create my first module and also in app.js we didn't take exports as a variable is it global?
My output :
Node Tutorial
N Tutorial
Undefined
What is this undefined?

How to use topclient in taobao in node js

I have taken reference from few sites
node js topclient
taobao node package
node-taobao-topclient
What I did:
I installed node-taobao-topclient
My code:
TopClient = require('node-taobao-topclient');
const client = new TopClient({
'appkey': 'xxxx',
'appsecret': 'xxxxx',
'REST_URL': 'http://gw.api.taobao.com/router/rest'
});
client.execute('taobao.wlb.imports.general.consign', {
"session" : "620260160ZZ61473fc31270a2c1f5dcc0efdff78b4c58312482635690",
'trade_order_id':'245033103766976',
'resource_id':'5044440108577',
'store_code':'Tran_Store_775585',
'first_logistics':'123',
'first_waybillno':'123',
'sender_id':'228',
'cancel_id':'228'
}, function(error, response) {
if (!error) console.log(response);
else console.log(error);
})
When I run above code I get error :
TypeError: TopClient is not a constructor
As I am new to node I don't how to exactly use such packages as on reference websites they are using it like:
TopClient = require('./topClient').TopClient;
My node-taobao-topclient package looks like below:
Any guidance on how I can use this API in node would be highly appreciated.
I have used for instalation :
npm i taobao-topclient
I have a correct compilation with :
const TopClient = require('taobao-topclient');
const client = new TopClient({
'appkey': aliexpress_app_key,
'appsecret': aliexpress_app_secret,
'REST_URL': 'http://gw.api.taobao.com/router/rest'
});
I have read the library and they do an exports directly from TopClient, so is not necesary to call it again , in the library at the top :
const request = require('request')
const util = require('./topUtil')
module.exports = class TopClient {
constructor (options) {
const opts = options || {}
if (!opts.appkey || !opts.appsecret) {
...............
If you call it again with another point .TopClient, dont found anything.
The following fragament works well:
TopClient = require('node-taobao-topclient').default;

Nodejs illegal operation on a directory

Im trying to compile a folder of markdown files into a single PDF with markdown-pdf NPM package.
I have a simple script to do the job:
var mpdf = require('markdown-pdf');
var fs = require('fs');
var mDocs = fs.readdirSync('./understandinges6/manuscript/');
mDocs = mDocs.map(function(d) { return 'understandinges6/manuscript/' + d });
var Book = 'understandinges6.pdf';
mpdf().concat.from(mDocs).to(Book, function() {
console.log("Created", Book);
});
But when i execute the script, this error appears:
events.js:154
throw er; // Unhandled 'error' event
^
Error: EISDIR: illegal operation on a directory, read
at Error (native)
It's weird because i'm in my home folder with the respective permissions. I'm specifying the output folder/file in the script and just reading with fs.readdirSync.
Any idea about this?
mDocs = mDocs.map(function(d) { return 'understandinges6/manuscript/' + d }); you forgot to add "./". Rewrite to mDocs = mDocs.map(function(d) { return './understandinges6/manuscript/' + d });
Cool, i get the problem here:
In the manuscripts/ folder are a images/ sub-folder with some png's. When the scripts tryed to read and transform images/ from .md to .pdf the error was fired.
Here is the array with the images/ inside:
[ 'understandinges6/manuscript/00-Introduction.md',
'understandinges6/manuscript/01-Block-Bindings.md',
'understandinges6/manuscript/02-Strings-and-Regular-Expressions.md',
'understandinges6/manuscript/03-Functions.md',
'understandinges6/manuscript/04-Objects.md',
'understandinges6/manuscript/05-Destructuring.md',
'understandinges6/manuscript/06-Symbols.md',
'understandinges6/manuscript/07-Sets-And-Maps.md',
'understandinges6/manuscript/08-Iterators-And-Generators.md',
'understandinges6/manuscript/09-Classes.md',
'understandinges6/manuscript/10-Arrays.md',
'understandinges6/manuscript/11-Promises.md',
'understandinges6/manuscript/12-Proxies-and-Reflection.md',
'understandinges6/manuscript/13-Modules.md',
'understandinges6/manuscript/A-Other-Changes.md',
'understandinges6/manuscript/B-ECMAScript-7.md',
'understandinges6/manuscript/Book.txt',
'understandinges6/manuscript/images' ]
Solution? Just pop() the mDocs array (now just docs):
var mpdf = require('markdown-pdf');
var fs = require('fs');
var mDocs = fs.readdirSync('understandinges6/manuscript/');
var docs = mDocs.map(function(d) { return 'understandinges6/manuscript/' + d });
docs.pop();
var Book = 'understandinges6.pdf';
mpdf().concat.from(docs).to(Book, function() {
console.log("Created", Book);
});

module is not defined error

I am using nodejs in my meteor app and I added packages using mrt add npm and then in my client directory in packages.json I added skimlinksjs and its version and it is added to my app.
When I tried to using them in my app in server side code like this,
var res;
var skim = Meteor.require('skimlinksjs');
var apili = Meteor.require('/config.js');
skim.setup(apili.key);
skim.query({
searchFor: "title:\"moto g\"",
fq: "country:US"
}, function(err,data) {
res=data.skimlinksProductAPI.numFound;
}
);
return res;
and my config.js file is like this
module.exports = {
key: "xxxxxxx"
}
whenI'm running this application it is showing error like
module not defined
What went wrong with my code or is there any need to install other packages?
I just got the answer
Write this function in server side code
function returnAllResult()
{
var skimlinks = Meteor.require('skimlinksjs');
skimlinks.setup("xxx");
var skimlinks_query = Async.wrap(skimlinks.query);
var result = skimlinks_query({
searchFor: "title:\"moto g\"",
fq: "country:US",
rows:5
});
return result;
}
to know about asynchronous functions watch this
and then in my server side methods call this
apiresult:function()
{
var response = returnAllResult();
return response.skimlinksProductAPI.products[0].merchant;
}
that's it working fine now. Hope this helps someone

Resources