Answers for "file to array javascript"

1

javascript convert file to array

var fs = require('fs');
var text = fs.readFileSync("./mytext.txt", 'utf-8');
var textByLine = text.split('\n')
Posted by: Guest on December-01-2020
0

file to array javascript

const fs = require('fs')
const path = require('path')

function tempStorageWindows(nameFile, data) {
	fs.accessSync(path.resolve(process.env.TMP))
	let filePath = `${process.env.TMP}/`
	const fileExist = fs.existsSync(path.resolve(filePath, `${nameFile}`))

	if (!fileExist) {
		fs.writeFileSync(path.resolve(filePath, `${nameFile}`), `${data.trim()}`, { encoding: 'utf8' })
		const toArray = fs.readFileSync(path.resolve(filePath, `${nameFile}`), { encoding: 'utf-8' }).split(' ')
		return Array.from(
			new Set([
				...toArray
					.map((val) => val.trim().replace(/[\s]/gi, ','))
					.join('')
					.trim()
					.split(',')
			])
		)
	} else {
		fs.appendFileSync(path.resolve(filePath, `${nameFile}`), `\n${data.trim()}`, { encoding: 'utf-8' })
		const toArray = fs.readFileSync(path.resolve(filePath, `${nameFile}`), { encoding: 'utf-8' }).split(' ')
		return Array.from(
			new Set([
				...toArray
					.map((val) => val.trim().replace(/[\s]/gi, ','))
					.join('')
					.trim()
					.split(',')
			])
		)
	}
}

function tempStorageLinux(nameFile, data) {
	let filePath = `/tmp`
	const fileExist = fs.existsSync(path.resolve(filePath, `${nameFile}`))

	if (!fileExist) {
		fs.writeFileSync(path.resolve(filePath, `${nameFile}`), `${data.trim()}`, { encoding: 'utf8' })
		const toArray = fs.readFileSync(path.resolve(filePath, `${nameFile}`), { encoding: 'utf-8' }).split(' ')
		return Array.from(
			new Set([
				...toArray
					.map((val) => val.trim().replace(/[\s]/gi, ','))
					.join('')
					.trim()
					.split(',')
			])
		)
	} else {
		fs.appendFileSync(path.resolve(filePath, `${nameFile}`), `\n${data.trim()}`, { encoding: 'utf-8' })
		const toArray = fs.readFileSync(path.resolve(filePath, `${nameFile}`), { encoding: 'utf-8' }).split(' ')
		return Array.from(
			new Set([
				...toArray
					.map((val) => val.trim().replace(/[\s]/gi, ','))
					.join('')
					.trim()
					.split(',')
			])
		)
	}
}

function checkOs(nameFile, data) {
	if (process.platform === 'win32') {
		return tempStorageWindows(nameFile, data)
	} else {
		return tempStorageLinux(nameFile, data)
	}
}

const res = checkOs('index.txt', 'samsul')
console.log(res)
Posted by: Guest on July-15-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language