require('debug').enable('*')
It works ok for my program, but it does not work for packages that use debug too.
For example package needle, how to enable debug for this package?
How to enable debug for all the packages which use debug?
I want to switch on/off debug in runtime, without application restarting
const path = require('path')
const fs = require('fs')
fs.readdirSync('node_modules').forEach(f => {
try {
const debugPackage = path.join('./node_modules', f, '/node_modules/debug')
fs.statSync(debugPackage).isDirectory()
require(`./${debugPackage}/node.js`).enable('*')
}
catch (unused) {}
})
As a workaround
Related
this is how I used to used it in common modules.
const debuger=require('debug')("namespace")
I set an environmental variable DEBUG="namespace" and when i start the app, i can use the debugger.
However I could not figure out how to use it with import/export staments.
import debugger from "debug" // how can i pass () here
You can do:
import debug from 'debug';
const logger = debug('namespace');
logger('Starting App');
Actually, as the npm debug module exports a function directly (module.exports = (params) => {...), you can give the function whatever name you like, for example:
import createDebugMessages from 'debug';
const debug = createDebugMessages('namespace');
debug('Starting App');
This way, the original syntax for debugging does not even need to be changed.
It is possible to get the version of the current package via
const { version } = require('./package.json')
but how can I get the version number of an arbitrary, installed package without loading it?
I found a solution with require.resolve:
const path = require('path')
// get version number without requiring the module
function packageVersion(moduleName) {
const dir = path.dirname(require.resolve(moduleName))
return require(path.join(dir, 'package.json')).version
}
I'm writing package for Atom editor.
Can anyone help with persmission denied error I get when using fs-plus makeTree method in my package when running it on Mac? No errors on Windows.
I use fs-plus, the same module that Atom uses in its tree-view package (and tree-view works on Mac).
UPD: Adding screenshot, and some code:
New Folder option shown on the picture is implemented using the same module - fs-plus, and it works on Mac. I use just the same module, and the same method (fs-plus.makeTree) to create directory, but my implementation fails with Permission denied error.
My code:
import util from 'util';
import { sep } from 'path';
import fs from 'fs-plus';
const makeTreeAsync = util.promisify(fs.makeTree);
createTutorial(data) {
const { initialPath } = this;
const { fileName } = data;
const filePath = `${initialPath}${sep}${fileName}${sep}${fileName}.md`;
return makeTreeAsync(fileName)
.then(() => writeFileAsync(filePath, this.getContent(data)))
.then(() => filePath);
},
code from tree-view package:
path = require 'path'
fs = require 'fs-plus'
onConfirm: (newPath) ->
newPath = newPath.replace(/\s+$/, '') # Remove trailing whitespace
endsWithDirectorySeparator = newPath[newPath.length - 1] is path.sep
unless path.isAbsolute(newPath)
// some path preprocessing
return unless newPath
try
if fs.existsSync(newPath)
#showError("'#{newPath}' already exists.")
else if #isCreatingFile
// some code, we are not interested in as we 're creating directory
else
fs.makeTreeSync(newPath)
#emitter.emit('did-create-directory', newPath)
#cancel()
catch error
#showError("#{error.message}.")
Important note: my package is installed manually (copied to ~/<username>/.atom/packages) and then run npm i
After some time of debugging, I have a solution. I tried to use native fs.mkdir with no luck, but after I added mode as the second argument - it worked.
const _0777 = parseInt('0777', 8);
const mode = _0777 & (~process.umask());
fs.mkdir(<folderPath>, mode, () => {});
Hope, this will help someone.
I have set up an angular-cli project
(# Angular / cli: 1.0.0-rc.2 node: 6.10.0 os: linux x64)
With electron js (v1.6.2)
And I need to use the filesystem to create / delete .csv files and folders, but I can not do includ in the angular component
How could you configure the angular-cli to be able to: import fs from 'fs'?
You wouldn't configure Angular-CLI to use the NodeJS fs module.
In electron you have 2 processes; main and renderer. The main process controls items such as the browserWindow, which is essentially the 'window' the user sees when they open their app, and in turn this loads the html file for the view. Here, in the main process, you import the fs module.
In the render process, you would handle actions from the view, and send them to the main process. This is where you would use IPC to communicate via events to do something with the main process. Once that event is triggered, the render process takes the event and sends it to main. Main would do something with it, and open a file for example on the desktop.
I would recommend using the electron API demo application to see clear examples of this. Here is an example of print to pdf using FS (from the demo app).
Also, here is an electron application github example written by Ray Villalobos using React, which has some similar concepts that will show you how to integrate components in your app.
Render process:
const ipc = require('electron').ipcRenderer
const printPDFBtn = document.getElementById('print-pdf')
printPDFBtn.addEventListener('click', function (event) {
ipc.send('print-to-pdf')
})
ipc.on('wrote-pdf', function (event, path) {
const message = `Wrote PDF to: ${path}`
document.getElementById('pdf-path').innerHTML = message
})
Main Process:
const fs = require('fs')
const os = require('os')
const path = require('path')
const electron = require('electron')
const BrowserWindow = electron.BrowserWindow
const ipc = electron.ipcMain
const shell = electron.shell
ipc.on('print-to-pdf', function (event) {
const pdfPath = path.join(os.tmpdir(), 'print.pdf')
const win = BrowserWindow.fromWebContents(event.sender)
// Use default printing options
win.webContents.printToPDF({}, function (error, data) {
if (error) throw error
fs.writeFile(pdfPath, data, function (error) {
if (error) {
throw error
}
shell.openExternal('file://' + pdfPath)
event.sender.send('wrote-pdf', pdfPath)
})
})
})
You can try using const fs = (<any>window).require("fs"); within the component or better still, create a service.ts provider to handle i/o operations.
I have some of my entries in package.json defined as "*"
"dependencies": {
"express": "4.*",
"passport": "*",
"body-parser": "*",
"express-error-handler": "*"
},
I wan't to freeze those values to the current version. How can I know what version my packages are at run time? I don't mind checking one by one since I don't have many of them :)
BTW: I cannot do npm list --depth=0 because I cannot access the vm directly (PaaS restriction), just the logs.
You can use the fs module to read the directories in the node_modules directory and then read package.json in each of them.
var fs = require('fs');
var dirs = fs.readdirSync('node_modules');
var data = {};
dirs.forEach(function(dir) {
try{
var file = 'node_modules/' + dir + '/package.json';
var json = require(file);
var name = json.name;
var version = json.version;
data[name] = version;
}catch(err){}
});
console.debug(data['express']); //= 4.11.2
Just in case if you need the version on the front-end, there is an npm package just for this and it can be used both on client-side and server-side.
global-package-version
You can use it in your code like this
import globalPackageVersion from 'global-package-version';
// package name is 'lodash'
globalPackageVersion(require('lodash/package.json'));
// You can type 'packageVersion' in browser console to check lodash version
// => packageVersion = { lodash: '4.7.2'}
packageVersion becomes a global object when used in server side and becomes a window object when used on the client side. Works well with webpack and all other bundling tools.
Disclaimer: I am the author of this package :)
I've 'modernised' a bit #laggingreflex answer, this works on ES6+, node 10, tested on a lambda running in aws. It's an endpoint from an express app.
const fs = require("fs");
module.exports.dependencies = async (_req, res) => {
const dirs = fs.readdirSync("./node_modules");
const modulesInfo = dirs.reduce((acc, dir) => {
try {
const file = `${dir}/package.json`;
const { name, version } = require(file);
return { ...acc, [name]: version };
} catch (err) {}
}, {});
res.status(200).json(modulesInfo);
};
The accepted solution can be improved upon in both terms of performance and stability:
1: the package name IS THE directory. In typically cases where you are looking for a specific package, you do not need to load every module.
2: this code will not run on all os due to the way the paths are formed
3: using require means the path needs to be relative to the current file (this would only work if your file is located at the top of your project folder & along side node_modules). In most cases, using readFile or readFileSync is a easier approach.
const fs = require('fs');
const path = require('path');
const dirs = fs.readdirSync('node_modules');
const data = {};
//add ones you care about
const trackedPackages = ['express', 'passport', 'body-parser'];
dirs.forEach(function(dir) {
if(trackedPackages.indexOf(dir) > -1){
try{
const json = JSON.parse(
fs.readFileSync(path.join('node_modules', dir, 'package.json'), 'utf8')
);
data[dir] = json.version;
}catch(e){
console.log(`failed to read/parse package.json for ${dir}`, e);
}
}
});
console.debug(data['express']); //= 4.11.2