用js根据下面的json,创建path中的文件,需要先判断文件是否存在 { "pages": [ { "path": "pages/index/index", "style": { "navigationBarTitleText": "洗了么" } }, { "path": "pages/user/login", "style": { "navigationBarTitleText": "登录" } }, { "path": "pages/user/register", "style": { "navigationBarTitleText": "注册" } },
时间: 2023-08-08 07:08:40 浏览: 50
你可以使用Node.js的fs模块来判断文件是否存在,并创建文件。下面是一个使用JavaScript实现的示例代码:
```javascript
const fs = require('fs');
const path = require('path');
const json = {
"pages": [
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "洗了么"
}
},
{
"path": "pages/user/login",
"style": {
"navigationBarTitleText": "登录"
}
},
{
"path": "pages/user/register",
"style": {
"navigationBarTitleText": "注册"
}
}
]
};
for (const page of json.pages) {
const filePath = path.join(__dirname, page.path + '.js');
if (fs.existsSync(filePath)) {
console.log(`File ${page.path}.js already exists.`);
} else {
fs.writeFileSync(filePath, '');
console.log(`File ${page.path}.js created successfully.`);
}
}
```
上述代码首先通过`fs.existsSync()`函数判断文件是否存在,然后使用`fs.writeFileSync()`函数创建文件。`path.join()`函数用于拼接文件路径,`__dirname`表示当前脚本的目录路径。
你可以将上述代码保存为一个`.js`文件,然后在Node.js环境中运行它。运行后,它会根据JSON中的`pages`数组中的每个页面路径创建相应的文件,并在控制台输出相关信息。