Giter VIP home page Giter VIP logo

node-util's Introduction

util Build Status

Node.js's util module for all engines.

This implements the Node.js util module for environments that do not have it, like browsers.

Install

You usually do not have to install util yourself. If your code runs in Node.js, util is built in. If your code runs in the browser, bundlers like browserify or webpack (up to version 4 -- see this documentation for how to include polyfills like util in webpack 5+) also include the util module.

But if none of those apply, with npm do:

npm install util

Usage

var util = require('util')
var EventEmitter = require('events')

function MyClass() { EventEmitter.call(this) }
util.inherits(MyClass, EventEmitter)

Browser Support

The util module uses ES5 features. If you need to support very old browsers like IE8, use a shim like es5-shim. You need both the shim and the sham versions of es5-shim.

To use util.promisify and util.callbackify, Promises must already be available. If you need to support browsers like IE11 that do not support Promises, use a shim. es6-promise is a popular one but there are many others available on npm.

API

See the Node.js util docs. util currently supports the Node 8 LTS API. However, some of the methods are outdated. The inspect and format methods included in this module are a lot more simple and barebones than the ones in Node.js.

Contributing

PRs are very welcome! The main way to contribute to util is by porting features, bugfixes and tests from Node.js. Ideally, code contributions to this module are copy-pasted from Node.js and transpiled to ES5, rather than reimplemented from scratch. Matching the Node.js code as closely as possible makes maintenance simpler when new changes land in Node.js. This module intends to provide exactly the same API as Node.js, so features that are not available in the core util module will not be accepted. Feature requests should instead be directed at nodejs/node and will be added to this module once they are implemented in Node.js.

If there is a difference in behaviour between Node.js's util module and this module, please open an issue!

License

MIT

node-util's People

Contributors

bdjnk avatar bernardmcmanus avatar commanderroot avatar defunctzombie avatar feross avatar goto-bus-stop avatar lukechilds avatar matrixfrog avatar snyamathi avatar trysound avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-util's Issues

Transfer ownership to an Org

@defunctzombie You are in the envious position of having a super popular module with a long history. But it doesn't look like you have been able to keep this project properly maintained. The npm module hasn't been updated in 4 years, and this module no longer has all the same features that the core "util" module provides. As @CMCDragonkai points out, forking is undesirable because the fork would no longer have the coveted "util" package name on npm. Many of us would love to see some of the outstanding issues closed and PRs merged. Would it be possible to transfer stewardship from your personal Github account to a group org, as well as transfer the npm package ownership to a group? I know both @mikeal and @sindresorhus - who contributed to the promisify PR are well established member in the node.js community and would be responsible co-maintainers. I'm obviously lesser known but have co-maintained tree-kill which is also downloaded a lot and was in a similar situation two years ago when I offered to co-maintain it. I don't have a strong opinion about what org util should belong to (browserify? a new one?) or who the members are, I just would like it to be owned and maintained by the community so we can start merging some of the outstanding PRs.

TextEncoder, TextDecoder

I typically do:

const {TextEncoder, TextDecoder} = require('util')

but now I'm building a React Native app and had to actually install this package npm i util, however the methods above I see are missing. where can I get them from and why are they not included in this package?

util security consultation

In the process of using the component (util), we analyzed and evaluated the password security,

The following types of suspected security problems were found:

  1. Secret Keyword

1 of the above problems have been found. We hope to get technical support from your organization for evaluation or modification. For details, please contact: mao.biao @ zte.com.cn

Inconsistent behaviour with node inherits

I have a node class that inherits Event emitter:

function MyClass() {
    EventEmitter.call(this);
}
util.inherits(MyClass, EventEmitter);

This class also has it's prototype object with methods:

MyClass.prototype.foo = function() {};

When I run my code on node (5.4) everything runs smoothly, but once webpack'ed the MyClass prototype gets squashed and only the EventEmitter methods survive.

Webpack 5

FYI, my understanding is that Webpack 5 does not automatically include this package by default, so this package's documentation may need to be updated 🙂

Module not found: Error: Can't resolve './support/isBuffer'

I get this error:

ERROR in ./node_modules/util/util.js
Module not found: Error: Can't resolve './support/isBuffer' in '<REDACTED>'
 @ ./node_modules/util/util.js 526:19-48
 @ ./node_modules/asn1-ts/dist/node/asn1.js
 @ ./source/AuthenticationFramework/index.ts
 @ ./source/index.ts
 @ multi ./source/index.ts

I believe this package is required by TypeScript. My code does not use it directly.

This is on a MacBook Air, whose output of uname -a yields this output:

Darwin <REDACTED> 18.2.0 Darwin Kernel Version 18.2.0: Mon Nov 12 20:24:46 PST 2018; root:xnu-4903.231.4~2/RELEASE_X86_64 x86_64

The fix is for me to open the package add .js to the end of the ./support/isBuffer in this line:

https://github.com/defunctzombie/node-util/blob/cfbf5d0acf112759a8aa7c2339a1694c52cf82d6/util.js#L536

NPM Version: 6.5.0
Node Version: v11.1.0

circular dependency on util.inherits

Hi,

I am having problems with using multiparty, which uses fd-slicer, which then uses util.inherits. I was looking as to why util.inherits became null. I looked at the code and saw that util.inherits require the inherits package. I looked at the inherits package, and it exports the util.inherits value.

I was wondering what happened? why the circular dependency?

How to promisify tmp-promise.file

As stated in documentation at https://npmjs.com/package/tmp-promise

Asynchronous file creation

import { file } from 'tmp-promise'

(async () => {
  const {fd, path, cleanup} = await file();
  // work with file here in fd
  cleanup();
})(); 

but instead I used this code:

const tmpFile = util.promisify(require('tmp-promise').file);
console.log('output', await tmpFile()); // output /tmp/tmp-2113950-dGDocFSAEGpd

I was expecting to see the three values: fd, path, cleanup but the returned value is only a string. How can I simplify promisification whilst also having access to those other values? I don't think I can destroy the tempfile or remove the callback after I am finished working with it.

util.inspect() on Errors does not include stack trace

util.inspect(new Error('foo')) in Node prints the stack trace of the error:

Error: foo
    at repl:1:15
    at Script.runInThisContext (vm.js:122:20)
    at REPLServer.defaultEval (repl.js:334:29)
    at bound (domain.js:395:14)
    at REPLServer.runBound [as eval] (domain.js:408:12)
    at REPLServer.onLine (repl.js:641:10)
    at REPLServer.emit (events.js:187:15)
    at REPLServer.EventEmitter.emit (domain.js:441:20)
    at REPLServer.Interface._onLine (readline.js:301:10)
    at REPLServer.Interface._line (readline.js:673:8)

This shim however just returns

[Error: foo]

Which is really bad if this is used as part of a logging tool.

Output of object seems buggy

> const util = require('util');
> util.inspect({a:1})
'{ a: 1 }'
> util.inspect(Object.create({a:1}))
'{}'
> util.inspect(Object.create({a:1}).a)
'1'
node --version
v6.10.0
grep version node_modules/util/package.json 
"version": "0.10.3"    

util.inspect() options maxArrayLength, breakLength

Does anyone know a browser-compatible inspect module that supports them, or can add support for them here?

Using [email protected], Node.js v6.9.4, npm v3.10.10, Ubuntu 14.04.5 LTS trusty:

var nums = [ 1, 2, 3, 4, 5 ],
  opts = { depth: null, maxArrayLength: 2, breakLength: 2 };
console.log("node:", require("util").inspect(nums, opts));
console.log("util:", require("util/util.js").inspect(nums, opts));

prints:

node: [ 1,
  2,
  ... 3 more items ]
util: [ 1, 2, 3, 4, 5 ]

Upgrading to node v4/v5 version

Hello @defunctzombie. I was just wondering whether you considered upgrading the utils to match the new features of the util module introduced by node >=4. Specifically ES2015 data types support for util.inspect? Would you accept a PR concerning this issue?

Reliance on `process.env.NODE_DEBUG`

This code will fail if process or process.env does not exist:

node-util/util.js

Lines 109 to 110 in 6b82825

if (process.env.NODE_DEBUG) {
var debugEnv = process.env.NODE_DEBUG;

We ran into this with vite.js 2.8.x which has another convention (https://vitejs.dev/guide/env-and-mode.html#env-variables).
node-util should probably have a safe fallback for when this environment variable does not exist (assume production build?).

We used a workaround described here: visgl/deck.gl#6134 (comment)

i find a error about isBuffer function

when i build use rollup, i find my project dist have a error about exports.isBuffer = require('./support/isBuffer');
my dist don't have this files (/support/isBuffer
image
)

At Sveltekit project process is not defined in util.js

image

my pachage.json:

	"devDependencies": {
		"@playwright/test": "^1.30.0",
		"@sveltejs/adapter-auto": "^1.0.2",
		"@sveltejs/adapter-netlify": "^1.0.0-next.88",
		"@sveltejs/kit": "^1.3.10",
		"@typescript-eslint/eslint-plugin": "^5.50.0",
		"@typescript-eslint/parser": "^5.50.0",
		"eslint": "^8.33.0",
		"eslint-config-prettier": "^8.6.0",
		"eslint-plugin-svelte3": "^4.0.0",
		"prettier": "^2.8.3",
		"prettier-plugin-svelte": "^2.9.0",
		"prisma": "^4.14.1",
		"rome": "^11.0.0",
		"svelte": "^3.55.1",
		"svelte-check": "^3.0.3",
		"tslib": "^2.5.0",
		"typescript": "^4.9.5",
		"vite": "^4.1.1",
		"vitest": "^0.25.8"
	},
	"type": "module",
	"dependencies": {
		"@lucia-auth/adapter-prisma": "^2.0.0",
		"@picocss/pico": "^1.5.7",
		"@prisma/client": "^4.9.0",
		"lucia-auth": "^1.7.0",
		"svelte-select": "^5.7.0",
		"xrpl": "^2.11.0"
	}

When the server is up, this error appears. I have to say that it has appeared suddenly. The project has not had any problems until now. The only thing I did was to use process.env.VARIABLE in a script when it was not the valid way. When I removed this usage, this error appeared, which is already a node error.
I cleared the cache and it doesn't work either.

circular reference cause `inherits()` became empty object

the line below refs to inherits() from inherits module, but inherits module reference back to util module by checking the implementation on util module first, causing the first require('inherits') to returns empty object (default exports is empty object), if then util.inherits() gets call immediately it will throw.

problematic line in question:
https://github.com/browserify/node-util/blame/ef984721db7150f651800e051de4314c9517d42c/util.js#L592

the line needs to be updated to require('inherits/inherits_browser')

Uncaught RangeError: Wrong length!

Hi,

As per my understanding, when using webpack ^5.0.0 version, we need to install utils manually and include it in fallback.
Like this

module.exports = {
  devtool: 'source-map',
  entry: entries,
  output: {
    path: PATHS.outputFolder,
    library: {
      type: 'var',
      name: 'Library'
    },
    filename: PATHS.outputFileName
  },
  mode: ENVIRONMENT,
  resolve: {
    extensions: ['.js', '.jsx'],
    fallback: {
      stream: false,
      path: false,
      zlib: false,
      crypto: false,
      util: require.resolve('util/')                    //SEE THIS
    }
  },
  module: {
    rules: [babelLoader, combinedStyleLoader, rawCSSLoader]
  },
  plugins: [
    new webpack.IgnorePlugin({ resourceRegExp: /^\.\/locale$/, contextRegExp: /moment$/ }),
    new webpack.ProvidePlugin({ process: 'process/browser', Buffer: ['buffer', 'Buffer'] })                       //SEE THIS
  ]
};

But after doing that
The project builds
and while running the localhost in browser -
I am getting the following error. - (which seems to be related to this package only)

    at $ (polyfill.min.js:2:6057)
    at new ArrayBuffer (polyfill.min.js:2:6174)
    at Object../node_modules/util/support/types.js (types.js:296:1)
    at __webpack_require__ (bootstrap:19:1)
    at Object../node_modules/util/util.js (util.js:467:1)
    at __webpack_require__ (bootstrap:19:1)
    at Object../node_modules/jws/lib/data-stream.js (data-stream.js:4:12)
    at __webpack_require__ (bootstrap:19:1)
    at Object../node_modules/jws/lib/sign-stream.js (sign-stream.js:3:18)
    at __webpack_require__ (bootstrap:19:1)

Tried different versions of Utils package - no success

is there any resolution ?
or
Any alternate way that i can try some other package or something ?

the name `fn` is defined multiple times when using `swc-loader`

I have an ejected CRA with a custom webpack loader. I use swc-loader instead of babel-loader for faster compile time. Actually, I add @walletconnect/web3-provider into my app. I got an error to include { util: require.resolve('util/') } into resolve.fallback webpack configuration. After that error was fixed, I got the error again like this

ERROR in ./node_modules/util/util.js
Module build failed (from ./node_modules/swc-loader/src/index.js):
Error: 
  × the name `fn` is defined multiple times
     ╭─[/media/data/SIDE_PROJECTS/webpack-react-ts-inversify-web-worker/node_modules/util/util.js:617:5]
 617 │ var fn = original[kCustomPromisifiedSymbol];
     ·     ─┬
     ·      ╰── previous definition of `fn` here
 618 │     if (typeof fn !== 'function') {
 619 │       throw new TypeError('The "util.promisify.custom" argument must be of type Function');
 620 │     }
 621 │     Object.defineProperty(fn, kCustomPromisifiedSymbol, {
 622 │       value: fn, enumerable: false, writable: false, configurable: true
 623 │     });
 624 │     return fn;
 625 │   }
 626 │ 
 627 │   function fn() {
     ·            ─┬
     ·             ╰── `fn` redefined here
     ╰────

could you please refactor the variable/function declaration name in order to solve my problem?

var fn = original[kCustomPromisifiedSymbol];

function fn() {

Cannot Find TypeScript Definitions

Hello!

Apologize for being a dingus on this.

I've tried

yarn add --registry=https://registry.npmjs.org @types/util

But this is what I get

dev ±✚  ⬡ v12.17.0  yarn add --registry=https://registry.npmjs.org @types/util
yarn add v1.22.5
[1/4] 🔍  Resolving packages...
error An unexpected error occurred: "https://registry.npmjs.org/@types%2futil: Not found".
info If you think this is a bug, please open a bug report with the information provided in "/Users/lknecht/Repositories/palantir-test-data-helpers/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

Can you provide guidance on how to add type definitions for this library?

Outdated dependency `inherits` causes trouble upstream; Webpack 2.

I encountered Error Uncaught TypeError: util.inherits is not a function while upgrading to webpack 2.

I traced the cause to "inherits": "2.0.1" instead of "^2.0.1" or the like. This has a cascading effect from inherits to util to assert to node-libs-browser and finally, to webpack itself.


Adding to my package.json:

"dependencies": {
  "inherits": "^2.0.3"

and to my webpack.config.js:

resolve: {
  alias: {
    inherits$: path.resolve(__dirname, 'node_modules/inherits')

is my current hideous workaround.

Installation on ubuntu 14.04 of 0.10.1, 0.10.2 and 0.10.3 fails with invalid json

I've tried to install bower-art-resolver, which uses a.o. the package util, but it fails due to not able to install util.
OS: Ubuntu 14.04
npm: 1.3.10
nodejs: 0.10.25

npm install -g [email protected]
works ok
npm install -g util
as well as 0.10.1, 0.10.2 and 0.10.3
fail with:

npm ERR! registry error parsing json
npm ERR! SyntaxError: Unexpected token 
npm ERR! �R�n�0����)�Nۧ 9�\��"0Hq)ёD�K�P
                                       �{w�p�KЃ��>ff�s��A�k.���F�K�ꓩS59$��(���U��
npm ERR! ���e�Q5F�4ހ<�<�߾�8B��Jf�y����Aq�3�`t���B��:�{�җ�'��ҳ�2��Q/%���^�,D��#ӹ���7}��ɱ#@��Ezq��ط|��E▒�B5Ƈ4�L�iI�H*���H\�r94ȓ�?�hr�0mL���2���)����2gW��▒������P�ciS~�H?"����f,v5u��ެvf��껻�~lw`�}���L�t�kc�{��UЪ�UY                       P\�e��'�>�e��-\�2o�.�J<����
                                   ���[�|��
npm ERR! %�m
npm ERR!     at Object.parse (native)
npm ERR!     at RegClient.<anonymous> (/usr/share/npm/node_modules/npm-registry-client/lib/request.js:238:23)

util.deprecate causes a stack overflow in browser

When util.js is bundled with browserify and run in browser, util.deprecate falls into an infinite loop here because process is not namespaced to global - it's only global within the context of the browserify bundle.

I can see where this would fall to @substack considering this deviates from the node environment, but I can also see why they would not want to set window.process from within a bundle. Checking typeof process rather than isUndefined(global.process) would be a simple solution.

Regardless, the --no-deprecation check should occur first to provide a way to avoid this.

Demo here.

Undeclared use of node's `process` causes exception in browser

Webpack 5 no longer ships polyfills for nodejs builtin modules, and recommends using this module if a module need util, and the module README does say it should work in a browser. However, the module causes a exception when importing the resulting bundle in the browser:

vendor.2cdb7b12f7e46077b4bd.js:92301 Uncaught ReferenceError: process is not defined

This is causes by this code, which expects to be able to use the nodejs process module without importing it:

if (process.env.NODE_DEBUG) {

Checking of process.env

On a line 109 is a code if (process.env.NODE_DEBUG) { which apparently checks for node process environment variables. But when the code is imported in a browser, as it is intended, the process variable is not defined which causes error and premature finish of the code execution. This defies purpose of the package. Please repair the condition.

License file please?

Hi,

Me again! Same question about this one too, please:

Please would it be possible to add a message about the license in the README or a separate LICENSE file? Or define it in the package.json?

Thanks again,

Peter

Sync with Node.js master

This is just a meta issue to update the whole module. So far it supports parts and other things are missing or somewhat outdated. It would be good to sync the whole project. One of the things that we should look into is what Browser support should be achieved. I personally would like to skip IE support. It is pretty hard to backport all changes that are necessary to support the Internet Explorer 11 (even though the current worldwide usage is still around 3%).

NPM@3 causes unwanted module overwrite

Before NPM version 3.0.0, I could use modules that require()'d this module, and then go ahead and use the Node core util module all I wanted. But now in NPM@3, the entire dependency tree is installed as flat as possible in the node_modules folder. This means that if I use a module that uses this module, I can no longer use the native util module anymore, because this one overwrites it. I did not put this module in my package.json as a dependency, an yet I am forced to use it. This should NOT be possible. If it's important to provide mirrors of the Node core modules in NPM, they should be under a different name. This wouldn't cause any problems, but it would solve this one.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.