本文整理匯總了TypeScript中fs.readdirSync函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript readdirSync函數的具體用法?TypeScript readdirSync怎麽用?TypeScript readdirSync使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了readdirSync函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1:
getDirectories: (dir) => fs.readdirSync(dir),
示例2: readdirSync
.then(() => oldNumberOfFiles = readdirSync('dist').length)
示例3: getFiles
export function getFiles(srcpath: string): string[] {
return fs.readdirSync(srcpath).filter(function (file: string) {
return fs.statSync(path.join(srcpath, file)).isFile();
});
}
示例4: start
export default function start(serverDataPath: string) {
dataPath = serverDataPath;
SupCore.log(`Using data from ${dataPath}.`);
process.on("uncaughtException", onUncaughtException);
loadConfig();
const { version, superpowers: { appApiVersion: appApiVersion } } = JSON.parse(fs.readFileSync(`${__dirname}/../package.json`, { encoding: "utf8" }));
SupCore.log(`Server v${version} starting...`);
fs.writeFileSync(`${__dirname}/../public/superpowers.json`, JSON.stringify({ version, appApiVersion, hasPassword: config.server.password.length !== 0 }, null, 2));
// SupCore
(global as any).SupCore = SupCore;
SupCore.systemsPath = path.join(dataPath, "systems");
// List available languages
languageIds = fs.readdirSync(`${__dirname}/../public/locales`);
languageIds.unshift("none");
// Main HTTP server
mainApp = express();
mainApp.use(cookieParser());
mainApp.use(handleLanguage);
mainApp.get("/", (req, res) => { res.redirect("/hub"); });
mainApp.get("/login", serveLoginIndex);
mainApp.get("/hub", enforceAuth, serveHubIndex);
mainApp.get("/project", enforceAuth, serveProjectIndex);
mainApp.use("/projects/:projectId/*", serveProjectWildcard);
mainApp.use("/", express.static(`${__dirname}/../public`));
mainHttpServer = http.createServer(mainApp);
mainHttpServer.on("error", onHttpServerError.bind(null, config.server.mainPort));
io = socketio(mainHttpServer, { transports: [ "websocket" ] });
// Build HTTP server
buildApp = express();
buildApp.get("/", redirectToHub);
buildApp.get("/systems/:systemId/SupCore.js", serveSystemSupCore);
buildApp.use("/", express.static(`${__dirname}/../public`));
buildApp.get("/builds/:projectId/:buildId/*", (req, res) => {
const projectServer = hub.serversById[req.params.projectId];
if (projectServer == null) { res.status(404).end("No such project"); return; }
let buildId = req.params.buildId as string;
if (buildId === "latest") buildId = (projectServer.nextBuildId - 1).toString();
res.sendFile(path.join(projectServer.buildsPath, buildId, req.params[0]));
});
buildHttpServer = http.createServer(buildApp);
buildHttpServer.on("error", onHttpServerError.bind(null, config.server.buildPort));
loadSystems(mainApp, buildApp, onSystemsLoaded);
// Save on exit and handle crashes
process.on("SIGINT", onExit);
process.on("message", (msg: string) => { if (msg === "stop") onExit(); });
}
示例5: mapLines
const createDTS = () => {
const header = `//
// Autogenerated from scripts/danger-dts.ts
//
import * as GitHub from "github"
declare module "danger" {
`
const footer = `}
`
let fileOutput = ""
const extras = ["source/platforms/messaging/violation.ts"]
const dslFiles = fs.readdirSync("source/dsl").map(f => `source/dsl/${f}`)
dslFiles.concat(extras).forEach(file => {
// Sometimes they have more stuff, in those cases
// offer a way to crop the file.
const content = fs.readFileSync(file).toString()
if (content.includes("/// End of Danger DSL definition")) {
fileOutput += content.split("/// End of Danger DSL definition")[0]
} else {
fileOutput += content
}
fileOutput += "\n"
})
// The definition of all the exposed vars is inside
// the Dangerfile.js file.
const allDangerfile = fs.readFileSync("source/runner/Dangerfile.ts").toString()
const moduleContext = allDangerfile
.split("/// Start of Danger DSL definition")[1]
.split("/// End of Danger DSL definition")[0]
// we need to add either `declare function` or `declare var` to the interface
const context = mapLines(moduleContext, (line: string) => {
if (line.length === 0 || line.includes("*")) {
const newLine = line.trim()
// Make sure TSLint passes
if (newLine.startsWith("*")) {
return " " + newLine
}
return newLine
}
if (line.includes("export type")) {
return line
}
if (line.includes("(")) {
return "function " + line.trim()
}
if (line.includes(":")) {
return "const " + line.trim()
}
return ""
})
fileOutput += context
// Remove all JS-y bits
fileOutput = fileOutput
.split("\n")
.filter(line => {
return !line.startsWith("import") && !line.includes("* @type ")
})
.join("\n")
const trimmedWhitespaceLines = fileOutput.replace(/\n\s*\n\s*\n/g, "\n")
const noRedundantExports = trimmedWhitespaceLines
.replace(/export interface/g, "interface")
.replace(/export type/g, "type")
const indentedBody = mapLines(noRedundantExports, line => (line.length ? ` ${line}` : ""))
return header + indentedBody + footer
}
示例6: getDirectories
function getDirectories(path: string): string[] {
return filter<string>(_fs.readdirSync(path), dir => fileSystemEntryExists(combinePaths(path, dir), FileSystemEntryKind.Directory));
}
示例7: readdirSync
const getDirectories = (source: any) =>
readdirSync(source).map(name => join(source, name)).filter(isDirectory);
示例8: readdirSync
.then(() => {
const main = readdirSync('./dist').find(name => !!name.match(/main.[a-z0-9]+\.bundle\.js/));
expectFileToMatch(`dist/${main}`, /bootstrapModuleFactory\(/);
})
示例9:
return service.copyFile(source.resource, target, true).then(res => { // CONWAY.js => conway.js
assert.equal(fs.existsSync(res.resource.fsPath), true);
assert.ok(fs.readdirSync(testDir).some(f => f === 'conway.js'));
});
示例10: readFilesOrURLsInDirectory
async function readFilesOrURLsInDirectory(d: string): Promise<TypeSource[]> {
const files = fs
.readdirSync(d)
.map(x => path.join(d, x))
.filter(x => fs.lstatSync(x).isFile());
// Each file is a (Name, JSON | URL)
const sourcesInDir: TypeSource[] = [];
const graphQLSources: GraphQLTypeSource[] = [];
let graphQLSchema: Readable | undefined = undefined;
let graphQLSchemaFileName: string | undefined = undefined;
for (let file of files) {
const name = typeNameFromFilename(file);
let fileOrUrl = file;
file = file.toLowerCase();
// If file is a URL string, download it
if (file.endsWith(".url")) {
fileOrUrl = fs.readFileSync(file, "utf8").trim();
}
if (file.endsWith(".url") || file.endsWith(".json")) {
sourcesInDir.push({
kind: "json",
name,
samples: [await readableFromFileOrURL(fileOrUrl)]
});
} else if (file.endsWith(".schema")) {
sourcesInDir.push({
kind: "schema",
name,
uris: [fileOrUrl]
});
} else if (file.endsWith(".gqlschema")) {
messageAssert(graphQLSchema === undefined, "DriverMoreThanOneGraphQLSchemaInDir", {
dir: dataDir
});
graphQLSchema = await readableFromFileOrURL(fileOrUrl);
graphQLSchemaFileName = fileOrUrl;
} else if (file.endsWith(".graphql")) {
graphQLSources.push({
kind: "graphql",
name,
schema: undefined,
query: await getStream(await readableFromFileOrURL(fileOrUrl))
});
}
}
if (graphQLSources.length > 0) {
if (graphQLSchema === undefined) {
return messageError("DriverNoGraphQLSchemaInDir", { dir: dataDir });
}
const schema = parseJSON(await getStream(graphQLSchema), "GraphQL schema", graphQLSchemaFileName);
for (const source of graphQLSources) {
source.schema = schema;
sourcesInDir.push(source);
}
}
return sourcesInDir;
}
示例11: ExportToCsv
import * as fs from 'fs'
import { ExportToCsv } from 'export-to-csv'
const gamesDir = process.argv[2]
const csvFilename = `${gamesDir}/games.csv`
const csvExporter = new ExportToCsv({
fieldSeparator: ',',
quoteStrings: '"',
showLabels: true,
useKeysAsHeaders: true,
});
const lineRegex = /\[([^"]+) "(.+)"\]/
const allGameData = []
fs.readdirSync(gamesDir).sort().forEach(filename => {
const lines = fs.readFileSync(`${gamesDir}/${filename}`).toString().split('\n')
const gameData = {}
lines.forEach(line => {
if (line.startsWith('1.')) {
gameData['Moves'] = line.replace(/\r$/, '')
} else {
const match = line.match(lineRegex)
if (match) {
const [name, value] = match.slice(1, 3)
gameData[name] = value
}
}
})
allGameData.push(gameData)
})
const csvData = csvExporter.generateCsv(allGameData, true)
示例12: samplesFromDirectory
async function samplesFromDirectory(dataDir: string): Promise<TypeSource[]> {
async function readFilesOrURLsInDirectory(d: string): Promise<TypeSource[]> {
const files = fs
.readdirSync(d)
.map(x => path.join(d, x))
.filter(x => fs.lstatSync(x).isFile());
// Each file is a (Name, JSON | URL)
const sourcesInDir: TypeSource[] = [];
const graphQLSources: GraphQLTypeSource[] = [];
let graphQLSchema: Readable | undefined = undefined;
let graphQLSchemaFileName: string | undefined = undefined;
for (let file of files) {
const name = typeNameFromFilename(file);
let fileOrUrl = file;
file = file.toLowerCase();
// If file is a URL string, download it
if (file.endsWith(".url")) {
fileOrUrl = fs.readFileSync(file, "utf8").trim();
}
if (file.endsWith(".url") || file.endsWith(".json")) {
sourcesInDir.push({
kind: "json",
name,
samples: [await readableFromFileOrURL(fileOrUrl)]
});
} else if (file.endsWith(".schema")) {
sourcesInDir.push({
kind: "schema",
name,
uris: [fileOrUrl]
});
} else if (file.endsWith(".gqlschema")) {
messageAssert(graphQLSchema === undefined, "DriverMoreThanOneGraphQLSchemaInDir", {
dir: dataDir
});
graphQLSchema = await readableFromFileOrURL(fileOrUrl);
graphQLSchemaFileName = fileOrUrl;
} else if (file.endsWith(".graphql")) {
graphQLSources.push({
kind: "graphql",
name,
schema: undefined,
query: await getStream(await readableFromFileOrURL(fileOrUrl))
});
}
}
if (graphQLSources.length > 0) {
if (graphQLSchema === undefined) {
return messageError("DriverNoGraphQLSchemaInDir", { dir: dataDir });
}
const schema = parseJSON(await getStream(graphQLSchema), "GraphQL schema", graphQLSchemaFileName);
for (const source of graphQLSources) {
source.schema = schema;
sourcesInDir.push(source);
}
}
return sourcesInDir;
}
const contents = fs.readdirSync(dataDir).map(x => path.join(dataDir, x));
const directories = contents.filter(x => fs.lstatSync(x).isDirectory());
let sources = await readFilesOrURLsInDirectory(dataDir);
for (const dir of directories) {
let jsonSamples: Readable[] = [];
const schemaSources: SchemaTypeSource[] = [];
const graphQLSources: GraphQLTypeSource[] = [];
for (const source of await readFilesOrURLsInDirectory(dir)) {
switch (source.kind) {
case "json":
jsonSamples = jsonSamples.concat(source.samples);
break;
case "schema":
schemaSources.push(source);
break;
case "graphql":
graphQLSources.push(source);
break;
default:
return assertNever(source);
}
}
if (jsonSamples.length > 0 && schemaSources.length + graphQLSources.length > 0) {
return messageError("DriverCannotMixJSONWithOtherSamples", { dir: dir });
}
const oneUnlessEmpty = (xs: any[]) => Math.sign(xs.length);
if (oneUnlessEmpty(schemaSources) + oneUnlessEmpty(graphQLSources) > 1) {
return messageError("DriverCannotMixNonJSONInputs", { dir: dir });
}
if (jsonSamples.length > 0) {
//.........這裏部分代碼省略.........
示例13: return
#!/usr/bin/env node
import * as fs from 'fs';
import * as path from 'path';
import Tunnel from '../Tunnel';
const digdugPath = path.dirname(__dirname);
const tunnels = fs
.readdirSync(digdugPath)
.filter(function(name) {
return (
/[A-Z]\w+Tunnel\.js$/.test(name) &&
name !== 'NullTunnel.js' &&
name !== 'Tunnel.js' &&
name !== 'SeleniumTunnel.js'
);
})
.map(function(name) {
return name.slice(0, name.length - 3);
});
if (process.argv.length !== 3) {
console.log('usage: environments TUNNEL');
console.log();
console.log('Available tunnels:');
tunnels.forEach(function(tunnel) {
console.log(' ' + tunnel);
});
process.exit(1);
示例14: scanDirectory
/**
* scanDirectory
*
* @params directoryPath : string
* @return directoryFileNames : Array<string>
*/
private scanDirectory(directoryPath : string) : Array<string> {
return FileSystem.readdirSync(directoryPath);
}
示例15: ensureAppdataDirExists
fr.winKillProcessOnExit();
ensureAppdataDirExists();
const trainedModelFile = 'faceRecognition2Model_150.json';
const trainedModelFilePath = path.resolve(getAppdataPath(), trainedModelFile);
const dataPath = path.resolve('../../data');
const facesPath = path.resolve(dataPath, 'faces');
const classNames = ['sheldon', 'lennard', 'raj', 'howard', 'stuart'];
const detector = fr.FaceDetector();
const recognizer = fr.FaceRecognizer();
if (!fs.existsSync(trainedModelFilePath)) {
console.log('%s not found, start training recognizer...', trainedModelFile);
const allFiles = fs.readdirSync(facesPath);
const imagesByClass = classNames.map((c) =>
allFiles
.filter((f) => f.includes(c))
.map((f) => path.join(facesPath, f))
.map((fp) => fr.loadImage(fp))
);
imagesByClass.forEach((faces, label) =>
recognizer.addFaces(faces, classNames[label]));
fs.writeFileSync(trainedModelFilePath, JSON.stringify(recognizer.serialize()));
} else {
console.log('found %s, loading model', trainedModelFile);
// tslint:disable-next-line:no-var-requires