跳到主要内容

Node.js v14 到 v16

AugustinMauroy

Node.js v14 到 v16

!

本文介绍从 Node.js v14 到 v16 迁移的部分内容。 userland migrations 团队正在开发更多 codemod,以帮助你完成 迁移。

本页提供了一系列 codemod,帮助你将代码从 Node.js v14 迁移到 v16。

create-require-from-path

Node.js v16 已将 createRequireFromPath 函数(在 DEP0148 中已弃用)替换为现代的 createRequire 函数。此 codemod 会将已弃用函数的调用替换为上述现代替代方案。

此 codemod 的源代码可在 create-require-from-path 目录 中找到。

你可以在 Codemod Registry 中找到此 codemod。

示例:

- const { createRequireFromPath } = require('node:module');
+ const { createRequire } = require('node:module');

- const requireFromPath = createRequireFromPath('/path/to/module');
+ const require = createRequire('/path/to/module');

- const myModule = requireFromPath('./myModule.cjs');
+ const myModule = require('./myModule.cjs');

process-main-module

process.mainModule 属性已弃用,建议改用 require.main。此 codemod 将帮助你把旧的 process.mainModule 用法替换为新的 require.main 用法。

因此,此 codemod 处理 DEP0138。

此 codemod 的源代码可在 process-main-module 目录 中找到。

你可以在 Codemod Registry 中找到此 codemod。

示例:

- if (process.mainModule === "mod.js") {
+ if (require.main === "mod.js") {
    // CLI 小工具
  } else {
    // module 东西
  }

rmdir

fs.rmdir 函数已弃用,建议改用带有 { recursive: true } 选项的 fs.rm。此 codemod 将帮助你把旧的 fs.rmdir 函数替换为新的 fs.rm 函数。

因此,此 codemod 处理 DEP0147。

此 codemod 的源代码可在 rmdir 目录 中找到。

你可以在 Codemod Registry 中找到此 codemod。

示例:

  // 使用带有 recursive 选项的 fs.rmdir
- fs.rmdir(path, { recursive: true }, callback);
+ // 使用带有 recursive 和 force 选项的 fs.rm
+ fs.rm(path, { recursive: true, force: true }, callback);

  // 使用 fs.rmdirSync 的 recursive 选项
- fs.rmdirSync(path, { recursive: true });
+ // 使用带有 recursive 和 force 选项的 fs.rmSync
+ fs.rmSync(path, { recursive: true, force: true });

  // 使用带 recursive 选项的 fs.promises.rmdir
- fs.promises.rmdir(path, { recursive: true });
+ // 使用 fs.promises.rm 的 recursive 和 force 选项
+ fs.promises.rm(path, { recursive: true, force: true });

tmpDir-to-tmpdir

在 Node.js v16 中,tmpDir 函数已重命名为 tmpdir。此 codemod 将帮助你把所有 tmpDir 实例替换为 tmpdir。

因此,该 codemod 处理 DEP0022。

此 codemod 的源代码可在 tmpdir-to-tmpdir 目录 中找到。

你可以在 Codemod Registry 中找到此 codemod。

示例:

- import { tmpDir } from 'node:os';
+ import { tmpdir } from 'node:os';
- const foo = tmpDir()
+ const foo = tmpdir()