简体   繁体   中英

How can I call methods defined in a javascript file from terminal with parameters

I am working on a test mongodb database using mongoose with my query methods defined in a javascript file, I want to run some queries using this methods by calling them from the terminal (some of them, with parameters) using node js. I did not create any server, though I am familiar with creating routes and making queries using postman and I have written test that confirm the methods are working as expected, I want to run the queries trough the terminal as i am doing this for learning purposes only.

I will be glad if someone can suggest a node package that can read javascript files and make the methods/functions defined in them available to be called from terminal. I am also open to any other way I can achieve this.

I have tried to search online for a suitable npm package but I have not been lucky, I am quite new to MEAN stack and is still learning, the bottom line is I want to run mongoose queries on terminal using my own defined method in a file (and not mongo). a snippet of my code showing some of the methods are provided further clarifications. thank you.

module.exports = {
createRole: function(roleTitle) {

var roleInfo = {
    title: roleTitle
  },
  newRole = new models.Role(roleInfo);

newRole.save(function(err, roles) {

  if (err) {
    console.log(err);
  }
  return 'role saved';

});

},


getAllUsers: function() {

return models.User.find({}).sort({
    firstname: 'ascending'
  })
  .populate('role');

},

getAllDocuments: function(limit) {

return models.Document
  .find({})
  .limit(limit)
  .sort({
    date: 'descending'
  })
  .select('dateCreated permission contents')
  .populate('permission');
  }
}

Short answer: process.argv

#! /usr/bin/env node

function hiya(name) {
  console.log('Hello, ' + name)
}


console.log('node: ' + process.argv[0])
console.log('script path: ' + process.argv[1])

if (process.argv.length > 2)
  hiya(process.argv[2])
else hiya('world')

Output (of "node example" or "./example"):

node: node
script path: /home/julian/wave/example
Hello, world

Output (of "node example test" or "./example test"):

node: node
script path: /home/julian/wave/example
Hello, test

Assuming I got your question properly, you want to start a console, and use from it the methods defined in your module? If this is the case, it is simple. Node when started with no file is an interactive shell. So start it, import your module and then the methods will be available for you:

on the command line type node (+ enter).

then type

var MyModule = require('MyModule');

Next you can type MyModule.createRole(....)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM