双反斜杠在节点中打印相同的内容

Double backslash prints the same in node

本文关键字:打印 节点      更新时间:2023-09-26

我想创建一个目录字符串变量,它是'。''app''src''agorithms',以便在Windows平台上的节点中的exec函数中使用它。然而,即使在字符串中使用双反斜杠,它也不能正常工作。这是我的尝试;

λ node
> directory =  '.'app'src'algorithms';
'.appsrcalgorithms'
> directory =  '.''app''src''algorithms';
'.''app''src''algorithms'

您所拥有的一切都很好。在内部,它被存储为双反斜杠,因为这就是转义反斜杠在JS字符串中的工作方式。节点REPL将向您显示实际值。使用它时,它应该正确渲染。

> directory = '.''app''src''algorithms';
'.''app''src''algorithms'
> console.log(directory)
.'app'src'algorithms
> exec('explorer.exe ' + directory); //works

我认为使用路径处理与平台无关的工作的最佳方式是使用路径模块。例如

var path = require('path');
var directory = path.join('.', 'app', 'src', 'algorithms')