如何检查目录?

时间:2019-12-18 10:22:32

标签: javascript node.js

我有一段代码检查.json是否存在。我需要代码仅在特定文件夹中寻找.json。我该怎么办?

if (extName === '.json') { 
    const fullFileNamed = '../../theme-default/resource/i18n'
    // console.log (fullFileNamed, "fullFileNamed")

    if(fullFileNamed) {
      console.log ( fullFileNamed, "fullFileNamed")
      const fileContent = fs.readFileSync(fullFileName, 'utf8')
      console.log (fileContent, "fileContent")
    } 
}   

这是不正确的。怎么做对呢?

2 个答案:

答案 0 :(得分:0)

if条件很好,变量名称在const fileContent = fs.readFileSync(fullFileName, 'utf8')中拼写错误,应将其更正为const fileContent = fs.readFileSync(fullFileNamed, 'utf8')

if (extName === '.json') { 
    const fullFileNamed = '../../theme-default/resource/i18n'
    // console.log (fullFileNamed, "fullFileNamed")

    if(fullFileNamed) {
      console.log ( fullFileNamed, "fullFileNamed")
      const fileContent = fs.readFileSync(fullFileNamed, 'utf8')
      console.log (fileContent, "fileContent")
    } 
}  

答案 1 :(得分:0)

您可以使用fs.access(path[, mode], callback),可选的mode参数可用于检查文件的可访问性,例如fs.constants.F_OK检查文件是否存在,并且fs.constants.R_OK表示该文件可读。 (The full list of File Access Constants)

if (extName === '.json') { 
        const fullFileNamed = '../../theme-default/resource/i18n';
        // console.log (fullFileNamed, "fullFileNamed")
        // Check if the file exists in the current directory, and if it is readable.
        fs.access(fullFileNamed, fs.constants.F_OK | fs.constants.R_OK, (err) => {
          if (err) {
            console.error(`${fullFileNamed} ${err.code === 'ENOENT' ? 'does not exist' : 'is not readable'}`);
          } else {
            console.log(`${fullFileNamed} exists, and it is readable`);
            const fileContent = fs.readFileSync(fullFileNamed, 'utf8');
            console.log ('fileContent', fileContent);
          }
        });
}   

对于同步测试,请使用fs.accessSync(path[, mode])

try {
  fs.accessSync(fullFileNamed, fs.constants.F_OK | fs.constants.R_OK);
  console.log(`${fullFileNamed} exists, and it is readable`);
  const fileContent = fs.readFileSync(fullFileNamed, 'utf8');
  console.log ('fileContent', fileContent);
} catch (err) {
  console.error(`${fullFileNamed} ${err.code === 'ENOENT' ? 'does not exist' : 'is not readable'}`);
}