Calling already defined routes in other routes in Express NodeJS

Similar to what Gates said, but I would keep the function(req, res){} in your routes file. So I would do something like this instead: routes.js var myModule = require(‘myModule’); app.get(“/firstService/:query”, function(req,res){ var html = myModule.firstService(req.params.query); res.end(html) }); app.get(“/secondService/:query”, function(req,res){ var data = myModule.secondService(req.params.query); res.end(data); }); And then in your module have your logic split up … Read more

tslint Error – Shadowed name: ‘err’

You are using the same variable “err” in both outer and inner callbacks, which is prevented by tslint. If you want to use the same variable then “no-shadowed-variable”: false, otherwise do as below. fs.readdir(fileUrl, (readDirError, files) => { fs.readFile(path.join(fileUrl, files[0]), function (err, data) { if (!err) { res.send(data); } }); });

Redirecting output to a log file using node.js

Here’s an example of logging to file using streams. var logStream = fs.createWriteStream(‘./logFile.log’, {flags: ‘a’}); var spawn = require(‘child_process’).spawn, ls = spawn(‘ls’, [‘-lh’, ‘/usr’]); ls.stdout.pipe(logStream); ls.stderr.pipe(logStream); ls.on(‘close’, function (code) { console.log(‘child process exited with code ‘ + code); });

Verify access/group in Passport.js

You could create a simple middleware that checks the group: var needsGroup = function(group) { return function(req, res, next) { if (req.user && req.user.group === group) next(); else res.send(401, ‘Unauthorized’); }; }; app.get(‘/api/users’, passport.authenticate(‘local’), needsGroup(‘admin’), function(req, res) { … }); This assumes that the object stored in req.user has a property group. This object is … Read more

Package.json with multiple entrypoints

As you’re using ECMAScript modules, please refer to node.js docs on package entry points: In a package’s package.json file, two fields can define entry points for a package: “main” and “exports”. The “main” field is supported in all versions of Node.js, but its capabilities are limited: it only defines the main entry point of the … Read more

node js: does fs.rename overwrite file if already exists

Short answer: yes Long answer: I created a script to check it: var fs = require(‘fs’); Create two files: fs.writeFileSync(‘a.txt’,”This is a file”) fs.writeFileSync(‘b.txt’,”This is another file”) Rename: fs.renameSync(‘a.txt’,’b.txt’); Check if it was overriden: var text = fs.readFileSync(‘b.txt’, “utf-8”); console.log(text) // This is a file