$ npm install @putout/plugin-nodejs
Node.js is an open-source, cross-platform, JavaScript runtime environment.
(c) Nodejs.org
πPutout plugin adds ability to transform to new Node.js API and apply best practices.
npm i putout @putout/plugin-nodejs -D
{
"rules": {
"nodejs/add-missing-strict-mode": "on",
"nodejs/add-node-prefix": "on",
"nodejs/apply-inherit": "on",
"nodejs/apply-privately-required-file": "off",
"nodejs/apply-style-text": "on",
"nodejs/cjs-file": "off",
"nodejs/convert-buffer-to-buffer-alloc": "on",
"nodejs/convert-commonjs-to-esm": "off",
"nodejs/convert-default-export-to-default": "on",
"nodejs/convert-dirname-to-url": "on",
"nodejs/convert-esm-to-commonjs": "off",
"nodejs/convert-exportst-to-module-exports": "on",
"nodejs/convert-fs-promises": "on",
"nodejs/convert-promisify-to-fs-promises": "on",
"nodejs/convert-top-level-return": "on",
"nodejs/convert-url-parse-to-new-url": "on",
"nodejs/convert-url-to-dirname": "on",
"nodejs/declare": "on",
"nodejs/declare-after-require": "on",
"nodejs/group-require-by-id": "on",
"nodejs/mjs-file": "off",
"nodejs/remove-illegal-strict-mode": "on",
"nodejs/remove-process-exit": "on",
"nodejs/remove-top-level-process-exit": "on",
"nodejs/remove-useless-exports-assign": "on",
"nodejs/remove-useless-promisify": "on",
"nodejs/remove-useless-strict-mode": "on",
"nodejs/rename-file-cjs-to-js": "off",
"nodejs/rename-file-mjs-to-js": "off"
}
}
Strict mode makes several changes to normal JavaScript semantics:
- Eliminates some JavaScript silent errors by changing them to throw errors.
- Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode.
- Prohibits some syntax likely to be defined in future versions of ECMAScript.
(c) MDN
Add strict mode to CommonJS:
const a = require('b');
'strict mode';
const a = require('b');
Denosupports using Node.js built-in modules such asfs,path,process, and many more vianode: specifiers.(c) deno.land
Check out in πPutout Editor.
import fs from 'fs';
const path = require('path');
await import('path');
import fs from 'node:fs';
const path = require('node:path');
await import('node:path');
| Linter | Rule | Fix |
|---|---|---|
| π Putout | add-node-prefix |
β |
| β£ ESLint | prefer-node-protocol |
β |
'inherit'equivalent to['inherit', 'inherit', 'inherit']or[0, 1, 2](c) nodejs.org
Check out in πPutout Editor.
spawn('ls', [], {
stdio: [0, 1, 2],
});
spawn('ls', [], {
stdio: 'inherit',
});
Entries in the imports field must be strings starting with
#. Package imports permit mapping to external packages. This field defines subpath imports for the current package.(c) nodejs.org
Let's consider file structure:
/
|-- package.json {"imports": {"#is": {"default": "./lib/tokenize/is.js"}}}
|-- lib/
| `-- tokenize/
| `-- is.js "export const isPrev = () => {}"
| `-- expressions/
`-- spread-element.js "const {isPrev} = require('../is.js')"
In this case spread-element.js can be fixed:
const {isPrev} = require('../is.js');
const {isPrev} = require('#is');
Fixes TypeError:
TypeError [ERR_INVALID_ARG_VALUE]: The argument 'format' must be one of: 'reset', 'bold', 'dim', 'italic', 'underline', 'blink', 'inverse', 'hidden', 'strikethrough', 'doubleunderline', 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'bgBlack', 'bgRed', 'bgGreen', 'bgYellow', 'bgBlue', 'bgMagenta', 'bgCyan', 'bgWhite', 'framed', 'overlined', 'gray', 'redBright', 'greenBright', 'yellowBright', 'blueBright', 'magentaBright', 'cyanBright', 'whiteBright', 'bgGray', 'bgRedBright', 'bgGreenBright', 'bgYellowBright', 'bgBlueBright', 'bgMagentaBright', 'bgCyanBright', 'bgWhiteBright'. Received 'grey'
Check out in πPutout Editor.
styleText('grey', `${line}:${column}`);
styleText('gray', `${line}:${column}`);
Run convert-esm-to-commonjs for all *.cjs files with help of redlint.
Check out in πPutout Editor.
The
Buffer()function andnew Buffer()constructor are deprecated due to API usability issues that can lead to accidental security issues.(c) DEP0005
Check out in πPutout Editor.
const n = 100;
const buf = [];
new Buffer(123);
new Buffer(n);
new Buffer('hello');
new Buffer([]);
new Buffer(buf);
const n = 100;
const buf = [];
Buffer.alloc(123);
Buffer.alloc(n);
Buffer.from('hello');
Buffer.from([]);
Buffer.from(buf);
MockModuleOptions.defaultExportandMockModuleOptions.namedExportshave been consolidated into a single optionlMockModuleOptions.exportsto align with user expectations and other test runners.(c) Node.js v25.9.0:
Checkout in πPutout Editor.
mock.module('fs', {
defaultExport: hello,
namedExports: {
foo,
hello,
abc,
},
});
mock.module('fs', {
default: hello,
foo,
hello,
abc,
});
Only for ESM.
const {join} = require('path');
const path = require('path');
const file1 = join(__dirname, '../../package.json');
const file2 = path.join(__dirname, '../../package.json');
const file1 = new URL('../../package.json', import.meta.url);
const file2 = new URL('../../package.json', import.meta.url);
CommonJS is a module system supported in Node, it provides a
requirefunction, which can be used to access theexportsobject exposed by another file.(c) parceljs
Convert EcmaScript Modules to CommonJS.
import hello from 'world';
const hello = require('world');
Since exports = 5 wan't make any export, just change value of variable.
Checkout in πPutout Editor.
exports.x = 5;
module.exports.x = 5;
Convert fs.promises into form that will be simpler to use and convert to and from ESM.
const {readFile} = require('fs').promises;
const {readFile} = require('fs/promises');
const fs = require('fs');
const readFile = promisify(fs.readFile);
const {readFile} = require('fs/promises');
return;
process.exit();
The legacy URL API is deprecated. Please use the WHATWG URL API instead.
(c) nodejs.org
Checkout in Putout Editor.
const parsed = url.parse(req.url);
const parsed = new URL(req.url);
Only for CommonJS.
const {readFile} = require('fs/promises');
const file = new URL('../../package.json', import.meta.url);
const {readFile} = require('fs/promises');
const {join} = require('path');
const file = join(__dirname, '../../package.json');
Convert CommonJS EcmaScript Modules.
EcmaScript module syntax is the standard way to import and export values between files in JavaScript. The
importstatement can be used to reference a value exposed by theexportstatement in another file.(c) parceljs
const {join} = require('path');
const args = require('minimist')({
string: ['a', 'b'],
});
import {join} from 'path';
import minimist from 'minimist';
const args = minimist({
string: ['a', 'b'],
});
Checkout in πPutout Editor.
module.exports = () => {};
export default () => {};
const {readFile} = require('fs/promises');
await readFile(__filename);
import {readFile} from 'fs/promises';
import {fileURLToPath} from 'url';
const __filename = fileURLToPath(import.meta.url);
await readFile(__filename);
Add declarations to built-in node.js modules:
Based on @putout/operator-declare.
await readFile('hello.txt', 'utf8');
import {readFile} from 'fs/promises';
await readFile('hello.txt', 'utf8');
When you want to skip some declaration use dismiss:
{
"rules": {
"nodejs/declare": ["on", {
"dismiss": ["readFile"]
}]
}
}
Node.js follows the CommonJS module system, and the builtin
requirefunction is the easiest way to include modules that exist in separate files. The basic functionality ofrequireis that it reads a JavaScript file, executes the file, and then proceeds to return theexportsobject.(c) Nodejs.org
Check out in πPutout Editor.For ESM use esm/declare-imports-first.
const name = 'hello.txt';
const {readFile} = require('fs/promises');
const {readFile} = require('fs/promises');
const name = 'hello.txt';
Checkout in πPutout Editor. For ESM use esm/group-imports-by-sources.
const ss = require('../../bb/ss');
const d = require('../hello');
const react = require('react');
const {lodash} = require('lodash');
const fs = require('node:fs');
const b = require('./ss');
const m = require(x);
const c = 5;
const fs = require('node:fs');
const react = require('react');
const {lodash} = require('lodash');
const ss = require('../../bb/ss');
const d = require('../hello');
const b = require('./ss');
const m = require(x);
const c = 5;
Run convert-commonjs-to-esm for all *.cjs files with help of redlint.
Check out in πPutout Editor.
SyntaxError: "use strict" not allowed in function with non-simple parametersThe JavaScript exception"use strict" not allowed in functionoccurs when ause strictdirective is used at the top of a function with default parameters, rest parameters, or destructuring parameters.(c) MDN
Checkout in πPutout Editor.
function x1(...a) {
'use strict';
}
function x2(a, b = 3) {
'use strict';
}
function x3({a}) {
'use strict';
}
function x4([a]) {
'use strict';
}
function x5(...a) {
'use strict';
}
function x1(...a) {}
function x2(a, b = 3) {}
function x3({a}) {}
function x4([a]) {}
function x5(...a) {}
In most cases process.exit() is called from bin directory, if not - disable this rule using match.
-process.exit();
Top-level process.exit() has no sense (except debugging).
Checkout in β Putout Editor.
-process.exit();
Checkout in πPutout Editor.
exports = require('./abc.js');
module.exports = exports;
module.exports = require('./abc.js');
Takes a function following the common error-first callback style, i.e. taking an (err, value) => ... callback as the last argument, and returns a version that returns promises.
(c) nodejs.org
Remove useless promisify(). Checkout in πPutout Editor.
export const readSize = promisify(async (dir, options, callback) => {});
export const readSize = async (dir, options, callback) => {};
The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
(c) MDN
'strict mode';
import a from 'b';
import a from 'b';
Rename *.cjs files when type === "commonjs":
/
|-- package.json
`-- lib/
- `-- hello.cjs
+ `-- hello.js
Check out in πPutout Editor.
Rename *.mjs files when type === "module":
/
|-- package.json
`-- lib/
- `-- hello.mjs
+ `-- hello.js
Check out in πPutout Editor.
MIT
© 2010 - cnpmjs.org x YWFE | Home | YWFE