How to remove a node
Once you have found the node(s) you want to remove (see tree traversal), you can remove them.
Contents
Prerequisites
- Tree traversal — intro on how to walk trees and find specific nodes with
unist-util-visit
Removing a node
For the most part, removing nodes has to do with finding them first (see tree traversal), so let’s say we already have some code to find all emphasis nodes.
First, our example.md file:
Some text with *emphasis*.
Another paragraph with **importance** (and *more emphasis*).
And a module, example.js:
import fs from 'node:fs/promises'
import remarkParse from 'remark-parse'
import {unified} from 'unified'
import {visit} from 'unist-util-visit'
const document = await fs.readFile('example.md', 'utf8')
const tree = unified().use(remarkParse).parse(document)
visit(tree, 'emphasis', function (node) {
console.log(node)
})
(alias) module "node:fs/promises"
import fs
The fs/promises API provides asynchronous file system methods that return promises.
The promise APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur.
(alias) const remarkParse: Plugin<[(Readonly<Options> | null | undefined)?], string, Root>
import remarkParse
Add support for parsing from markdown.
- @this processor.
- @param Configuration (optional).
- @returns Nothing.
(alias) const unified: Processor<undefined, undefined, undefined, undefined, undefined>
import unified
(alias) function visit<Tree extends Node, Check extends Test>(tree: Tree, check: Check, visitor: BuildVisitor<Tree, Check>, reverse?: boolean | null | undefined): undefined (+1 overload)
import visit
Visit nodes.
This algorithm performs depth-first tree traversal in preorder (NLR) or if reverse is given, in reverse preorder (NRL).
You can choose for which nodes visitor is called by passing a test. For complex tests, you should test yourself in visitor, as it will be faster and will have improved type information.
Walking the tree is an intensive task. Make use of the return values of the visitor when possible. Instead of walking a tree multiple times, walk it once, use unist-util-is to check if a node matches, and then perform different operations.
You can change the tree. See Visitor for more info.
- @overload
- @overload
- @param tree Tree to traverse.
- @param testOrVisitor
unist-util-is-compatible test (optional, omit to pass a visitor). - @param visitorOrReverse Handle each node (when test is omitted, pass
reverse). - @param maybeReverse Traverse in reverse preorder (NRL) instead of the default preorder (NLR).
- @returns Nothing.
- @template {UnistNode} Tree Node type.
- @template {Test} Check
unist-util-is-compatible test.
(alias) module "node:fs/promises"
import fs
The fs/promises API provides asynchronous file system methods that return promises.
The promise APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur.
function readFile(path: PathLike | fs.FileHandle, options: ({
encoding: BufferEncoding;
flag?: OpenMode | undefined;
} & EventEmitter<T extends EventMap<T> = any>.Abortable) | BufferEncoding): Promise<string> (+2 overloads)
Asynchronously reads the entire contents of a file.
- @param path A path to a file. If a URL is provided, it must use the
file: protocol. If a FileHandle is provided, the underlying file will not be closed automatically. - @param options An object that may contain an optional flag. If a flag is not provided, it defaults to
'r'.
(alias) unified(): Processor<undefined, undefined, undefined, undefined, undefined>
import unified
(method) Processor<undefined, undefined, undefined, undefined, undefined>.use<[], string, Root>(plugin: Plugin<[], string, Root>, ...parameters: [] | [boolean]): Processor<Root, undefined, undefined, undefined, undefined> (+2 overloads)
Configure the processor to use a plugin, a list of usable values, or a preset.
If the processor is already using a plugin, the previous plugin configuration is changed based on the options that are passed in. In other words, the plugin is not added a second time.
Note: use cannot be called on frozen processors. Call the processor first to create a new unfrozen processor.
- @example There are many ways to pass plugins to
.use(). This example gives an overview:import {unified} from 'unified'
unified()
// Plugin with options:
.use(pluginA, {x: true, y: true})
// Passing the same plugin again merges configuration (to `{x: true, y: false, z: true}`):
.use(pluginA, {y: false, z: true})
// Plugins:
.use([pluginB, pluginC])
// Two plugins, the second with options:
.use([pluginD, [pluginE, {}]])
// Preset with plugins and settings:
.use({plugins: [pluginF, [pluginG, {}]], settings: {position: false}})
// Settings only:
.use({settings: {position: false}})
- @template {Array} [Parameters=[]]
- @template {Node | string | undefined} [Input=undefined]
- @template [Output=Input]
- @overload
- @overload
- @overload
- @param value Usable value.
- @param parameters Parameters, when a plugin is given as a usable value.
- @returns Current processor.
(alias) const remarkParse: Plugin<[(Readonly<Options> | null | undefined)?], string, Root>
import remarkParse
Add support for parsing from markdown.
- @this processor.
- @param Configuration (optional).
- @returns Nothing.
(method) Processor<Root, undefined, undefined, undefined, undefined>.parse(file?: Compatible | undefined): Root
Parse text to a syntax tree.
Note: parse freezes the processor if not already frozen.
Note: parse performs the parse phase, not the run phase or other phases.
- @param file file to parse (optional); typically
string or VFile; any value accepted as x in new VFile(x). - @returns Syntax tree representing
file.
(alias) visit<Root, "emphasis">(tree: Root, check: "emphasis", visitor: BuildVisitor<Root, "emphasis">, reverse?: boolean | null | undefined): undefined (+1 overload)
import visit
Visit nodes.
This algorithm performs depth-first tree traversal in preorder (NLR) or if reverse is given, in reverse preorder (NRL).
You can choose for which nodes visitor is called by passing a test. For complex tests, you should test yourself in visitor, as it will be faster and will have improved type information.
Walking the tree is an intensive task. Make use of the return values of the visitor when possible. Instead of walking a tree multiple times, walk it once, use unist-util-is to check if a node matches, and then perform different operations.
You can change the tree. See Visitor for more info.
- @overload
- @overload
- @param tree Tree to traverse.
- @param testOrVisitor
unist-util-is-compatible test (optional, omit to pass a visitor). - @param visitorOrReverse Handle each node (when test is omitted, pass
reverse). - @param maybeReverse Traverse in reverse preorder (NRL) instead of the default preorder (NLR).
- @returns Nothing.
- @template {UnistNode} Tree Node type.
- @template {Test} Check
unist-util-is-compatible test.
(parameter) node: Emphasis
(method) console.Console.log(...data: any[]): void
(parameter) node: Emphasis
Now, running node example.js yields (ignoring positions for brevity):
{
type: 'emphasis',
children: [ { type: 'text', value: 'emphasis', position: [Object] } ]
}
{
type: 'emphasis',
children: [ { type: 'text', value: 'more emphasis', position: [Object] } ]
}
As the above log shows, nodes are objects. Each node is inside an array at the children property of another node. In other words, to remove a node, it must be removed from its parents children.
The problem then is to remove a value from an array. Standard JavaScript Array functions can be used: namely, splice.
We have the emphasis nodes, but we don’t have their parent, or the position in the parent’s children field they are in. Luckily, the function given to visit gets not only node, but also that index and parent:
--- a/example.js
+++ b/example.js
@@ -7,6 +7,6 @@ const document = await fs.readFile('example.md', 'utf8')
const tree = unified().use(remarkParse).parse(document)
-visit(tree, 'emphasis', function (node) {
- console.log(node)
+visit(tree, 'emphasis', function (node, index, parent) {
+ console.log(node.type, index, parent?.type)
})
Yields:
emphasis 1 paragraph
emphasis 3 paragraph
parent is a reference to the parent of node, index is the position at which node is in parent’s children. With this information, and splice, we can now remove emphasis nodes:
--- a/example.js
+++ b/example.js
@@ -8,5 +8,9 @@ const document = await fs.readFile('example.md', 'utf8')
const tree = unified().use(remarkParse).parse(document)
visit(tree, 'emphasis', function (node, index, parent) {
- console.log(node.type, index, parent?.type)
+ if (typeof index !== 'number' || !parent) return
+ // Note: this is buggy, see next section.
+ parent.children.splice(index, 1)
})
+
+console.log(tree)
Yields:
{
type: 'root',
children: [
{
type: 'paragraph',
children: [
{type: 'text', value: 'Some text with '},
{type: 'text', value: '.'}
]
},
{
type: 'paragraph',
children: [
{type: 'text', value: 'Another paragraph with '},
{type: 'strong', children: [Array]},
{type: 'text', value: ' (and '},
{type: 'text', value: ').'}
]
}
]
}
This looks great, but beware of bugs. We are now changing the tree, while traversing it. That can cause bugs and performance problems.
When changing the tree, in most cases you should signal to visit how it should continue. More information on how to signal what to do next, is documented in unist-util-visit-parents.
In this case, we don’t want the removed node to be traversed (we want to skip it). And we want to continue with the node that is now at the position where our removed node was. To do that: return that information from visitor:
--- a/example.js
+++ b/example.js
@@ -1,7 +1,7 @@
import fs from 'node:fs/promises'
import remarkParse from 'remark-parse'
import {unified} from 'unified'
-import {visit} from 'unist-util-visit'
+import {SKIP, visit} from 'unist-util-visit'
const document = await fs.readFile('example.md', 'utf8')
@@ -9,8 +9,9 @@ const tree = unified().use(remarkParse).parse(document)
visit(tree, 'emphasis', function (node, index, parent) {
if (typeof index !== 'number' || !parent) return
- // Note: this is buggy, see next section.
parent.children.splice(index, 1)
+ // Do not traverse `node`, continue at the node *now* at `index`.
+ return [SKIP, index]
})
console.log(tree)
This yields the same output as before, but there’s no bug anymore. Nice, we can now remove nodes!
Replacing a node with its children
One more thing to make this example more useful: instead of dropping emphasis and its children, it might make more sense to replace the emphasis with its children.
To do that, we can do the following:
--- a/example.js
+++ b/example.js
@@ -9,7 +9,7 @@ const tree = unified().use(remarkParse).parse(document)
visit(tree, 'emphasis', function (node, index, parent) {
if (typeof index !== 'number' || !parent) return
- parent.children.splice(index, 1)
+ parent.children.splice(index, 1, ...node.children)
// Do not traverse `node`, continue at the node *now* at `index`.
return [SKIP, index]
})
Yields:
{
type: 'root',
children: [
{
type: 'paragraph',
children: [
{type: 'text', value: 'Some text with '},
{type: 'text', value: 'emphasis'},
{type: 'text', value: '.'}
]
},
{
type: 'paragraph',
children: [
{type: 'text', value: 'Another paragraph with '},
{type: 'strong', children: [Array]},
{type: 'text', value: ' (and '},
{type: 'text', value: 'more emphasis'},
{type: 'text', value: ').'}
]
}
]
}