xccjk / x-blog

学习笔记
17 stars 2 forks source link

node相关问题 #77

Closed xccjk closed 1 year ago

xccjk commented 2 years ago

__dirname is not defined in ES module scope in JS

es模块中使用__dirname时,会报错

The "__dirname is not defined in ES module scope" error occurs when we try to try to use the __dirname global variable in an ES module file. The __dirname or __filename global variables are not available in ECMAScript module files

解决方案:

import path from 'path';
import {fileURLToPath} from 'url';

const __filename = fileURLToPath(import.meta.url);

const __dirname = path.dirname(__filename);

console.log(path.join(__dirname, 'app'))
xccjk commented 2 years ago

node 格式化输出json

const str = JSON.stringify(data, "", "\t");

或者

const str = JSON.stringify(data, null, "\t");
xccjk commented 2 years ago

动态读取及写入json

读取:

const getPackageJson = (path) => {
  const packageJson = fs.readFileSync(path);
  return JSON.parse(packageJson);
}
packageJson('./package.json');

写入:

const writePackageJson = ({ path, json }) => {
  fs.writeFile(path, JSON.stringify(json, null, '\t'), (err) => {
    if (err) console.log('package.json修改失败: ', err);
    console.log('package.json修改成功!');
  })
}
writePackageJson({ path: './package.json', json: packageJson('./package.json') })
xccjk commented 2 years ago

判断文件夹是否存在

fs.existsSync(path)