Use command line npm modules as normal modules - node.js

I and my friends were wondering how to require and use a node module which was designed to be used in the CLI
For ex: The standard module is intended to be called via the command line by executing
standard "src/util/**/*.js" "test/**/*.js"
How do we get the same functionality by requiring it like other npm modules
For ex: const standard = require("standard");

First, you have to install the standard module using the following command.
npm install standard
Then you can use the various functions in the standard module's NodeJS API.
Example:
const standard = require('standard');
standard.lintFiles('/path/to/files/*.js', function (err, res) {
if (err) {
console.log(err);
} else {
console.log(res);
}
});

Related

How do I save a file and maybe ask for admin permissions?

I am making a game launcher for my games, and I want to be able to download the files from amazon s3, and install them into C:\Program Files directory. How do I do that, and also how do I ask for admin permissions if needed?
To write a file, you can use the built-in fs module.
Import the fs module.
const fs = require("fs");
Use the fs.writeFile() method.
const content = "Content for the program!";
fs.writeFile('C:\\Program Files\\program.txt', content, (err) => {
if (err) {
console.error(err);
return
}
// Code here if successful...
});
To check if your script is running with admin privileges, you can use the is-elevated module on npm.
Install is-elevated from npm (ignore the $).
$ npm install is-elevated
Use the import statement to add it in your code.
import isElevated from "is-elevated";
Call the method to see if your script is running with elevated privileges.
console.log(await isElevated());

Installing NPM Modules via the Frontend

I am working on an app wherein I would like to be able to install NPM modules via the frontend. I have no idea, though, how to do so. That is, I know how to do CRUD actions via the front end, but I don't know how to either interact with the command line or run command line functions via the front end.
Are there packages that can help with this or is this built into Node.js somehow?
In short, how can I connect my front-end to my backend in such a way that I can install an NPM package?
What you want is the child_process module. It's built-in so you don't need to install any additional module.
Mostly what you're looking for is either spawn() or exec().
For example, if you want to run npm install some_module you can do:
const { exec } = require('child_process');
let command = 'npm install some_module';
let options = { cwd: '/path/to/node/project' };
exec(command, options, (error, stdout, stderr) => {
// Do anything you want with program output here:
console.log('output:', stdout, stderr);
});
You may check the documentation for child_process in Node JS:
Child Process
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
The key difference between exec() and spawn() is how they return the data. As exec() stores all the output in a buffer, it is more memory intensive than spawn(), which streams the output as it comes.
Generally, if you are not expecting large amounts of data to be returned, you can use exec() for simplicity. Good examples of use-cases are creating a folder or getting the status of a file. However, if you are expecting a large amount of output from your command, then you should use spawn()
The easiest way to install an npm package via "the front end" is to have node spawn npm as a child process based off of the package name that the client provides.
var child = require('child_process').exec(`npm i ${package_name}`);
child.on('exit',function(){
//npm finished
});
This should install the module given that package_name is the name of the npm package, in the same directory that the script is running in. In terms of getting the package name from the front end to the back end, there are several different ways to do that.
You cannot run the your backend application without NPM modules installed, one thing that I think you can do is to make a plain nodejs file without any modules, which will receive the args when invoked, and you can use that args to the required modules, because that file will run with just core modules

Not able to require a node module

I'm new to node js and require js. I installed a node module via npm install(https://www.npmjs.org/package/box-view). The node_modules folder has a box-view/index.js containing:
module.exports = {
BoxView: BoxView,
createClient: function (key) {
return new BoxView(key);
}
};
When I try to access the module using require:
require ['box-view'], () ->
console.log("Ready")
I get:
GET http://127.0.0.1:9000/js/box-view.js 404 (Not Found).
Looks like I'm doing a basic mistake. Thanks in advance!
Node has a simple module loading system - files and modules are in one to one correspondence.
var boxView = require('box-view');
console.log("Ready");
I think problem is because you did a npm install box-view so it will be under node_modules/box_view/index.js.
But using require you are just saying require ['box-view'] so it's looking ./box-view.js
This will work
require(["node_modules/box-view/index"]
but this is not a good practice.
You should have a look on require node manual. It tells how to use requirejs with node.

Progmatically using npm from nodejs build script

I have a large project which contains multiple node application endpoints, each with their own package.json file.
I have a main build script (written in jake) which sets up a given environment, runs tests, packages apps etc.
So is there a way for the root build script to run "npm install" on the given directories.
I expect psudo code would be:
var npm = require("npm");
var package1Directory = "some-directory";
npm.install(packageDirectory);
Cannot find any documentation around this though so not sure if it is possible... so is it?
Yes, have a look at the docs:
var npm = require("npm")
npm.load(myConfigObject, function (er) {
if (er) return handlError(er)
npm.commands.install(["some", "args"], function (er, data) {
if (er) return commandFailed(er)
// command succeeded, and data might have some info
})
npm.on("log", function (message) { .... })
})
Also have a look at this example, which gives some more insights on how to use npm programmatically.

Can I npm link on a nodejitsu instance?

I'm trying to use a lib that I need to install and then link with npm. I don't see any clear path for me to access my server this way using the jitsu cli. How would I go about doing this?
I work for nodejitsu.
First, I believe your problem can be solved by using bundledDependencies in your package.json like so:
{
"bundledDependencies": [ "myModule", "myFork" ]
}
Then, when jitsu bundles your app for deployment (which uses npm), it will also bundle your dependency with it.
If the package is on a personal fork of a project on github, npm also can pull directly from a git url. Check out http://npmjs.org/doc/ for more information on ways to pull npm modules from non-registry sources.
Also: We have a dedicated support team which can be contacted either through support#nodejitsu.com or at #nodejitsu on irc.freenode.net .
Have you tried using npm programmatically? The docs give the following example:
var npm = require("npm")
npm.commands.install(["some", "args"], function (er, data) {
if (er) return commandFailed(er)
// command succeeded, and data might have some info
})
You can find the full docs here: https://github.com/isaacs/npm/blob/master/README.md
So in your case maybe you do: (in psuedo code)
npm.commands.install(['mylibarary'], function(er, data) {
if (er) { throw Error(); }
npm.commands.link( ... args ... function(er, data) {
... happy amazing awesome ...
});
});
You should also drop by the IRC room. The people there are very helpful.

Resources