I'm trying to create a simple application to compile mustache templates into static pages server side, here's what I've got so far:
var view = {
title: "Joe",
calc: function () {
return 2+4;
}
};
var mustache = require("mustache");
var template = require("./home.template");
var output = mustache.to_html(template, view);
console.log(output);
And my template looks like:
{{title}} spend {{calc}}
Any suggestions as to what is causing this to fail?
Here is the complete error message:
home.template:1
} spend {{calc}}
^
module.js:437
var compiledWrapper = runInThisContext(wrapper, filename, true);
^
SyntaxError: Unexpected token {
at Module._compile (module.js:437:25)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (/Users/MorehouseJ09/Documents/production_development/mustache/current/compiler.js:12:16)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
Any help would be great!
Use fs.readFile() to read your template in as a string. Require won't work unless it's requiring javascript code, not mustache code.
http://nodejs.org/api/fs.html#fs_fs_readfile_filename_encoding_callback
Edit
See if this works...
var mustache = require("mustache");
var fs = require("fs");
var view = {
title: "Joe",
calc: function () {
return 2+4;
}
};
fs.readFile('./home.template', 'utf-8', function (err, data) {
if (err) throw err;
var output = mustache.to_html(data, view);
console.log(output);
});
Related
I am beginner in node.js.
I am trying to call a very basic addition module saved in C:\wks\guru99 with file name: Node_03_addition.js. The calling application is also saved in the same location with the name: app.js
Addition Module:
var exports = module.exports = {};
exports.addNumber=function(a,b)
{
return a+b;
};
Application File:
var Addition = require('/.Node_03_addition.js');
console.log(Addition.addNumber(1,2));
when I run the application in cmd using node app.js
I am receiving the error that Module is not found. Can someone please help me with where I am going wrong here.
c:\wks\guru99>node app.js
internal/modules/cjs/loader.js:969
throw err;
^
Error: Cannot find module '/.Node_03_addition.js'
Require stack:
- c:\wks\guru99\app.js
[90m at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15)[39m
[90m at Function.Module._load (internal/modules/cjs/loader.js:842:27)[39m
[90m at Module.require (internal/modules/cjs/loader.js:1026:19)[39m
[90m at require (internal/modules/cjs/helpers.js:72:18)[39m
at Object.<anonymous> (c:\wks\guru99\app.js:1:16)
[90m at Module._compile (internal/modules/cjs/loader.js:1138:30)[39m
[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)[39m
[90m at Module.load (internal/modules/cjs/loader.js:986:32)[39m
[90m at Function.Module._load (internal/modules/cjs/loader.js:879:14)[39m
[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)[39m {
code: [32m'MODULE_NOT_FOUND'[39m,
requireStack: [ [32m'c:\\wks\\guru99\\app.js'[39m ]
}
SUGGESTION
// Node_03_addition.js
// Declare your function
const addNumber = function(a,b) {
return a + b;
};
// Export your function
module.exports = {
addNumber
};
// Application-File.js
// Import your module
const Addition = require('./Node_03_addition');
// Use it
console.log(Addition.addNumber(1,2)); // 3
Addition Module:
var exports = module.exports = {};
exports.addNumber=function(a,b)
{
return a+b;
};
Application File:
var Addition = require('./Node_03_addition.js');
console.log(Addition.addNumber(1,2));
No changes made to lang.js file since months ago but suddenly syntax error when trying to preview locally and can't deploy changes.
Not sure why this is happening - could somebody please kindly help? Many thanks!
Disclosure/warning: I have 0 programming knowledge.
MacBook:pty-bus Ying$ node index.js
/Users/Ying/Desktop/pty-bus/lang.js:19
...req.lang.marketing.global,
^^^
SyntaxError: Unexpected token ...
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/Ying/Desktop/pty-bus/index.js:20:36)
at Module._compile (module.js:571:32)
lang.js
var path = require('path');
function langMiddleware(req, res, next){
let lang = req.query.lang || 'en';
if(['es', 'en'].indexOf(lang) == -1) lang = 'en'
fs.readFile(path.join(__dirname, 'lang', lang + '.json'), 'utf8', function(err, data){
req.lang = JSON.parse(data);
req.langCode = lang;
next();
})
};
function render(req, res, template, vars={}){
let renderObj = {
...req.lang.marketing.global,
title: req.lang.titles[template],
site_title: req.lang.site_title,
site_description: req.lang.site_description,
...(req.lang.marketing[template] || {}),
lang: {...(req.lang.marketing.global.language || {})},
langCode: req.langCode,
...vars,
path: req.path
};
res.render(template, renderObj);
}
module.exports = { langMiddleware, render }
It looks like your ability to use spread operator has been removed. I would guess you have recently changed your node version, or edited either your babelrc or webpack config. Either way, I don't think it's anything wrong with your current code in that file.
Node.js v7.4.0 has V8 5.4 which supports ...operator for arrays, but not for objects. You need at least V8 6.0, i.e. the last Node.js 8 branch version will do (v8.15.0).
Tt looks like node v7.4.0 not support spread operator - change let renderObj = {...} to
let renderObj = {
title: req.lang.titles[template],
site_title: req.lang.site_title,
site_description: req.lang.site_description,
langCode: req.langCode,
path: req.path
};
Object.assign(renderObj,
req.lang.marketing.global,
(req.lang.marketing[template] || {}),
vars
);
renderObj.lang = Object.assign({}, (req.lang.marketing.global.language || {}));
I am currently following this example on shared behaviors for my mocha, sinon, and chai tests.
https://github.com/mochajs/mocha/wiki/Shared-Behaviours
Currently, I have tests that are suppose to be reused as I test my application.
In my shared test, I am passing a context which is going to pass an object component of a React store which i call var testObj = new ReactStore(data, ContainerModel);
Problem
I'm having trouble figuring out how to use my shared tests when I import them from the shared test file.
This is how the structure of the SharedTest.js looks like
var shouldBehaveLikeACustomDomain = function (context) {
//custom domain test
describe("Custom Domain", function () {
var domainData = context.domainData;
//Methods for extended class
describe("Methods", function () {
//test for refresh method
it("_refresh should call __onRefresh", function (done) {
var customDomainClass = class extends context.domain {
constructor (domainData, StoreContainer) {
super(domainData, StoreContainer);
}
//recaluclate some properties every time domainData is refreshed
__onRefresh() {
assert(true);
done();
}
};
var url = new RegExp("^http\\:\\/\\/example\\.com\\/api\\/logEntries\\/" + domainData + "(\\?(.*))?$", "i");
//server sends get request
context.respondWith("GET", url, function (request) {
try {
request.respond(200, {}, "{}");
}
catch (e) {
done(e);
}
});
var testCustomObj = new customDomainClass(domainData, StoreContainer);
testCustomObj._refresh();
});
//test load
it ("#Actions:load should call __.onLoad()", function () {
var isLoaded = false,
customDomainClass = class extends context.domain {
constructor (domainData, StoreContainer) {
super({}, domainData, StoreContainer);
}
//keep custom property up-to-date by using an onLoad hook
__onLoad() {
isLoaded = true;
}
};
//create default response
context.respondWith(SinonUtil.persistentResponse);
//create instance
var testCustomObj = new customDomainClass(domainData,StoreContainer);
testCustomObj.Actions().load(testCustomObj.get('id'));
assert.equal(isLoaded, true);
});
});
});
};
module.exports = shouldBehaveLikeACustomDomain;
AnotherTestFile.js
var shared = require(./SharedTest.js);
describe ('#Domains', function () {
beforeEach(function (){
var testObj = new ReactStore(data, ContainerModel);
});
shared.shouldBehaveLikeACustomDomain();
//some other tests here
});
Here is the error I am getting
C:\Users\Demon\Desktop\hapnin.js\test\EventStore.test.js:217
shared.shouldBehaveLikeACustomDomain(testObj);
^
TypeError: shared.shouldBehaveLikeACustomDomain is not a function
at Suite.<anonymous> (C:\Users\Demon\Desktop\hapnin.js\test\EventStore.test.js:217:16)
at Object.create (C:\Users\Demon\Desktop\hapnin.js\node_modules\mocha\lib\interfaces\common.js:114:19)
at context.describe.context.context (C:\Users\Demon\Desktop\hapnin.js\node_modules\mocha\lib\interfaces\bdd.js:44:27)
at Suite.<anonymous> (C:\Users\Demon\Desktop\hapnin.js\test\EventStore.test.js:215:5)
at Object.create (C:\Users\Demon\Desktop\hapnin.js\node_modules\mocha\lib\interfaces\common.js:114:19)
at context.describe.context.context (C:\Users\Demon\Desktop\hapnin.js\node_modules\mocha\lib\interfaces\bdd.js:44:27)
at Object.<anonymous> (C:\Users\Demon\Desktop\hapnin.js\test\EventStore.test.js:166:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at C:\Users\Demon\Desktop\hapnin.js\node_modules\mocha\lib\mocha.js:230:27
at Array.forEach (native)
at Mocha.loadFiles (C:\Users\Demon\Desktop\hapnin.js\node_modules\mocha\lib\mocha.js:227:14)
at Mocha.run (C:\Users\Demon\Desktop\hapnin.js\node_modules\mocha\lib\mocha.js:495:10)
at Object.<anonymous> (C:\Users\Demon\Desktop\hapnin.js\node_modules\mocha\bin\_mocha:469:18)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
This has nothing to do with Sinon, Mocha or Chai: this is simply to do with CommonJS and can be seen from the error message: you are not dealing with a function.
In your client code, you import ./SharedTest.js and try to reference a field on that module called shouldBehaveLikeACustomDomain. Then you get an error about there not being such a thing.
For you to have been able to use a field called shouldBehaveLikeACustomDomain, your module.exports would need to be an object containing a field with that name. It would look something like:
module.exports = { shouldBehaveLikeACustomDomain: shouldBehaveLikeACustomDomain };
It is not: you are directly exposing the function as the exported module.
module.exports = shouldBehaveLikeACustomDomain;
Therefore you only need to use the module directly in your code, not any embedded fields.
Instead of this
var shared = require(./SharedTest.js);
describe ('#Domains', function () {
beforeEach(function (){
var testObj = new ReactStore(data, ContainerModel);
});
shared.shouldBehaveLikeACustomDomain();
Just delete a few words:
const shouldBehaveLikeACustomDomain = require(./SharedTest.js);
describe ('#Domains', function () {
beforeEach(function (){
const testObj = new ReactStore(data, ContainerModel);
});
shouldBehaveLikeACustomDomain(); // this is missing a required argument
P.S. This still won't work, as your shouldBehaveLikeACustomDomain function requires an argument, which you are not passing in, but at least this answers your immediate question. Open another one if you have problems fixing this last one to avoid lowering Signal/Noise.
This code snippet seems not work, why?
var acorn = require("./node_modules/acorn/dist/acorn_loose");
/* Extend default Acorn's methods.*/
acorn.pluginsLoose.testPlug = function(looseParser) {
looseParser.extend('finishNode', function(nextMethod) {
return function(node, type) {
console.log(node, type);
return nextMethod.call(this, node, type);
};
});
};
var res = acorn.parse_dammit("alert(1", {ecmaVersion: 6, plugins: {testPlug: true}});
console.log(res)
Give us next error:
...\node_modules\acorn\dist\acorn.js:508
if (!plugin) throw new Error("Plugin '" + name + "' not found")
^
Error: Plugin 'testPlug' not found
at Parser.loadPlugins (...\node_modules\acorn\dist\acorn.js:508:26)
at new Parser (...\node_modules\acorn\dist\acorn.js:444:10)
at Object.tokenizer (...\node_modules\acorn\dist\acorn.js:3115:12)
at new LooseParser (...\node_modules\acorn\dist\acorn_loose.js:15:23)
at Object.parse_dammit (...\node_modules\acorn\dist\acorn_loose.js:1258:13)
at Object.<anonymous> (...\plugins_poc.js:16:17)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
Is it bug or I do something wrong?
Enviroment: idea intellij 16.
Update:
Chrome give the similar error.
var res = acorn.parse_dammit("alert(1", {ecmaVersion: 6, plugins: {testPlug: true}});
You need to use pluginsLoose instead of plugins here as well!
Background: User inputs details about a flight in app.js, which then prints it out in the console. Only one module is used from index.js, which contains an object prototype.
Problem: When I run the command "node app.js", I get the following error:
/Users/
UserName/Desktop/NodeTrainingWork/04/objectcreat/flight/index.js:3
var this.data = {
^^^^
SyntaxError: Unexpected token this
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:413:25)
at Object.Module._extensions..js (module.js:452:10)
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 Object.<anonymous> (/Users/UserName/Desktop/NodeTrainingWork/04/objectcreat/app.js:1:76)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
This is the index.js code:
var Flight = function() {
var this.data = {
number: null,
origin: null,
destination: null,
arrivalTime: null
};
this.fill = function(info) {
for (var prop in this.data) {
if (this.data[prop] != 'undefined') {
this.data[prop] = info[prop];
}
}
};
this.triggerArrival: function() {
this.data.arrivalTime = Date.now();
}
this.getInformation: function() {
return this.data;
}
};
module.exports = function(info) {
var instance = new Flight();
instance.fill(info);
return instance;
};
And this is the code in the app.js file:
var flight = require('./flight');
var pdxlax = {
number: 847,
origin: 'PDX',
destination: 'LAX'
};
var pl = flight(pdxlax);
pl.triggerArrival();
console.log(pl.getInformation());
var pk340 = {
number: 340,
origin: 'ISL',
destination: 'DXB'
};
var pk = flight(pk340);
pk.triggerArrival();
console.log(pk.getInformation());
I dont know where I am going wrong. From what I have learned, my way of creating a an object prototype is correct.
var is used to create a new variable, not to create a property on an object.
Remove var from the line that is erroring.