I generate some jS code on the front end and i want to write it to a js file by making an api call to a node server and i'm having some trouble with 1) ensuring the code isnt written to file as a literal string and 2) ensuring that multiple lines are preserved.
Here's my code for how ive attempted this:
//client
var bar = "mongolia"; //this value changes hence pulling it into variable
var jsCode = "function(){ \n
baz = foo(" + bar + "); \n
return baz*2;"
var data = {
code: jsCode
}
$http.post('api/code', data).success(function(savedCode){
console.log("successful and the saved code is", savedCode);
});
//server
'use strict';
var jf = require('jsonfile'),
util = require('util');
var codeFile = './code/js/autoGen.js';
exports.addCode = function(req, res) {
var newCode = req.body.code;
//write to file
return jf.writeFile(codeFile, newCode, function(err) {
if(!err) {
return res.json({newCode: newCode});
}
else {
return res.send(err);
}
});
};
When i run this, I get a syntax error in my jsCode definition.
jsonfile? Can't you just usevar fs = require('fs'); fs.writeFile(//...?returns in yourexports.addCode